What are the best practices for handling user input in PHP to prevent errors and vulnerabilities like SQL injection?

To prevent errors and vulnerabilities like SQL injection when handling user input in PHP, it is important to sanitize and validate the input data before using it in database queries. One common approach is to use prepared statements with parameterized queries to securely interact with the database.

// Example of using prepared statements to prevent SQL injection
// Assume $conn is a valid database connection object

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

// Prepare a SQL statement with a parameterized query
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $userInput);

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

// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Handle the retrieved data
}

// Close the statement and connection
$stmt->close();
$conn->close();