How can PHP scripts be secured against SQL injection vulnerabilities?

To secure PHP scripts against SQL injection vulnerabilities, developers should use prepared statements with parameterized queries instead of directly inserting user input into SQL queries. This approach helps to separate SQL logic from user input, preventing attackers from manipulating SQL queries through input fields.

// 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 user input to the parameter
$stmt->bindParam(':username', $_POST['username']);

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

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