How can SQL injection vulnerabilities be mitigated when handling user input in PHP scripts?

SQL injection vulnerabilities can be mitigated by using prepared statements with parameterized queries in PHP scripts. This approach separates SQL code from user input, preventing malicious SQL commands from being executed.

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

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

// Bind parameters to prevent SQL injection
$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':password', $_POST['password']);

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

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