What are the best practices for handling user input in PHP when querying a database?

When handling user input in PHP when querying a database, it is important to sanitize and validate the input to prevent SQL injection attacks. One way to do this is by using prepared statements with parameterized queries, which separate the SQL query from the user input. This helps to ensure that the input is treated as data and not executable code.

// Example of using prepared statements to handle user input
$user_input = $_POST['user_input'];

// Prepare the SQL query 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', $user_input);

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

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