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

SQL injection vulnerabilities can occur when user inputs are not properly sanitized before being used in SQL queries, allowing malicious users to manipulate the query and potentially access or modify the database. To prevent SQL injection attacks, it is important to use parameterized queries or prepared statements to handle user inputs securely in PHP.

// Example of using prepared statements to prevent SQL injection

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

// Prepare a SQL statement with a placeholder for 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);

// Do something with the results
foreach ($results as $row) {
    echo $row['username'] . '<br>';
}