What are some best practices for securing user input in PHP scripts to prevent SQL injection?

SQL injection is a common attack where malicious SQL statements are inserted into input fields to manipulate the database. To prevent SQL injection in PHP scripts, it is essential to sanitize and validate user input before using it in SQL queries. One way to do this is by using prepared statements with parameterized queries, which separate the SQL code from the user input.

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

// Sanitize and validate user input
$userInput = filter_var($_POST['user_input'], FILTER_SANITIZE_STRING);

// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $userInput, PDO::PARAM_STR);

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

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

// Use the results as needed
foreach ($results as $row) {
    echo $row['username'] . '<br>';
}