How can SQL injection vulnerabilities be prevented when writing PHP code for database queries?
SQL injection vulnerabilities can be prevented in PHP code by using prepared statements with parameterized queries. This method separates the SQL query logic from the user input, preventing malicious SQL code from being injected into the query.
// Using prepared statements to prevent SQL injection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $_POST['username']);
$stmt->execute();
$results = $stmt->fetchAll();