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

To prevent SQL injection vulnerabilities in database operations in PHP, it is crucial to sanitize and validate user input before using it in SQL queries. One of the best practices is to use prepared statements with parameterized queries, which separate SQL code from user input. Additionally, escaping special characters in user input can help prevent injection attacks.

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

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

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

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

// Display results or perform further operations
foreach ($results as $row) {
    echo $row['username'] . "<br>";
}