How can SQL injection vulnerabilities be prevented when using PHP to query a database?

SQL injection vulnerabilities can be prevented in PHP by using prepared statements with parameterized queries. This approach separates the SQL query logic from the user input, preventing malicious SQL code from being injected into the query.

// 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 AND password = :password");

// Bind the parameters to the statement
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);

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

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