How can PHP developers effectively prevent SQL injection when modifying user data in a database?
To prevent SQL injection when modifying user data in a database, PHP developers should use prepared statements with parameterized queries. This method separates the SQL query logic from the user input, making it impossible for malicious input to alter the query structure.
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare("UPDATE users SET email = :email WHERE id = :id");
// Bind parameters to the query
$stmt->bindParam(':email', $email);
$stmt->bindParam(':id', $id);
// Sanitize user input
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$id = intval($_POST['id']);
// Execute the query
$stmt->execute();