How can SQL Injection vulnerabilities be prevented in PHP code when querying a database?

SQL Injection vulnerabilities can be prevented in PHP code by using prepared statements with parameterized queries. This approach separates the SQL query logic from the user input, making it impossible for malicious input to alter the query structure. By binding user input to parameters in the query, the database engine can distinguish between code and data, effectively preventing SQL Injection attacks.

// 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("SELECT * FROM users WHERE username = :username");

// Bind user input to the parameter
$username = $_POST['username'];
$stmt->bindParam(':username', $username);

// Execute the prepared statement
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);