What are best practices for preventing SQL injection vulnerabilities in PHP scripts that interact with databases?

SQL injection vulnerabilities can be prevented in PHP scripts by using prepared statements with parameterized queries instead of directly inserting user input into SQL queries. This helps to sanitize user input and prevent malicious SQL code from being executed.

// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a SQL statement with placeholders
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username AND password = :password");

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

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

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