What are the best practices for handling user input validation in PHP when checking against a MySQL database?

When handling user input validation in PHP against a MySQL database, it is important to sanitize and validate the input to prevent SQL injection attacks and ensure data integrity. One common approach is to use prepared statements with parameterized queries to safely interact with the database.

// Example of handling user input validation in PHP with MySQL database

// Assuming $conn is the database connection object

// Sanitize and validate user input
$userInput = $_POST['user_input'];
$cleanInput = mysqli_real_escape_string($conn, $userInput);

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

// Process the query results
$result = $stmt->get_result();
if($result->num_rows > 0) {
    // User input is valid
} else {
    // User input is invalid
}

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