What best practices should be followed when handling user input in PHP to prevent SQL syntax errors?

To prevent SQL syntax errors when handling user input in PHP, it is essential to sanitize and validate the input before using it in SQL queries. One common approach is to use prepared statements with parameterized queries, which helps prevent SQL injection attacks by separating the SQL code from the user input data.

// Example of using prepared statements to prevent SQL syntax errors
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Sanitize and validate user input
$user_input = filter_var($_POST['user_input'], FILTER_SANITIZE_STRING);

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

// Bind the sanitized user input to the placeholder
$stmt->bindParam(':username', $user_input, PDO::PARAM_STR);

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

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

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