What are the best practices for handling user input in PHP to prevent SQL injection attacks?

To prevent SQL injection attacks in PHP, it is important to sanitize and validate user input before using it in database queries. One way to do this is by using prepared statements with parameterized queries, which separate the SQL query from the user input. This helps to prevent malicious SQL code from being injected into the query.

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

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

// Prepare a SQL query using a prepared statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $cleanInput, PDO::PARAM_STR);
$stmt->execute();

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

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