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 essential to sanitize and validate user input before using it in database queries. One way to achieve this is by using prepared statements with parameterized queries. This approach separates the SQL query from the user input, making it impossible for malicious input to alter the query structure.

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

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

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

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

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

// Process the results as needed
foreach ($results as $row) {
    // Do something with the data
}