What are the recommended methods for sanitizing input data before inserting it into a database using PHP?
When inserting data into a database using PHP, it is important to sanitize the input to prevent SQL injection attacks. One recommended method is to use prepared statements with parameterized queries, which automatically escape input data. Another method is to use PHP's built-in functions like mysqli_real_escape_string() to escape special characters. Additionally, you can validate input data using regular expressions or filter_input() function before inserting it into the database.
// Using prepared statements with parameterized queries
$stmt = $pdo->prepare("INSERT INTO table_name (column1, column2) VALUES (:value1, :value2)");
$stmt->bindParam(':value1', $value1);
$stmt->bindParam(':value2', $value2);
$stmt->execute();
// Using mysqli_real_escape_string()
$value = mysqli_real_escape_string($conn, $input);
// Validating input data
if (preg_match("/^[a-zA-Z0-9]+$/", $input)) {
// Insert data into database
} else {
echo "Invalid input data";
}