How can SQL Injection vulnerabilities be mitigated in PHP scripts that handle user input?

SQL Injection vulnerabilities in PHP scripts can be mitigated by using prepared statements with parameterized queries. This helps to prevent malicious SQL queries from being injected into the database by escaping user input. By using prepared statements, the database engine can distinguish between SQL code and data, reducing the risk of 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 the user input to the parameter
$stmt->bindParam(':username', $_POST['username']);

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

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