What are the best practices for handling user input in PHP applications to maintain the integrity of MySQL queries and prevent malicious attacks?

When handling user input in PHP applications, it is crucial to sanitize and validate the input to prevent SQL injection attacks and maintain the integrity of MySQL queries. One common best practice is to use prepared statements with parameterized queries to securely interact with the database. Additionally, input validation should be performed to ensure that only expected data is passed to the database.

// Example of using prepared statements with parameterized queries to handle user input securely

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

// Prepare a SQL statement with a placeholder for the user input
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

// Bind the user input to the placeholder
$stmt->bindParam(':username', $_POST['username']);

// Execute the prepared statement
$stmt->execute();

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

// Loop through the results and do something with them
foreach ($results as $row) {
    echo $row['username'] . "<br>";
}