What are the best practices for validating user input in PHP to prevent SQL injection attacks and ensure data integrity?

To prevent SQL injection attacks and ensure data integrity, it is essential to validate user input before using it in SQL queries. One way to achieve this is by using prepared statements with parameterized queries in PHP. This approach separates SQL logic from user input, making it impossible for malicious input to modify the SQL query structure.

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

// Validate user input
$userInput = $_POST['user_input'];
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $userInput);
$stmt->execute();

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

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