How can SQL injection vulnerabilities be mitigated in PHP scripts that interact with a database?

SQL injection vulnerabilities can be mitigated in PHP scripts by using prepared statements with parameterized queries. This approach separates SQL code from user input, preventing malicious SQL queries from being executed. By using prepared statements, input data is treated as data, not as SQL commands, making it much harder for attackers to inject malicious code.

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

// Prepare a SQL query using a parameterized query
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username AND password = :password');

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

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

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