What are the best practices for handling form input validation in PHP to prevent SQL injection attacks?

To prevent SQL injection attacks when handling form input validation in PHP, it is crucial to sanitize and validate user input before using it in database queries. One way to achieve this is by using prepared statements with parameterized queries to ensure that user input is treated as data, not as SQL commands. Additionally, using functions like `filter_var()` or `mysqli_real_escape_string()` can help sanitize input and prevent malicious SQL injection attempts.

// Example of handling form input validation to prevent SQL injection attacks

// Assuming $db is your database connection object

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

// Prepare a SQL statement using prepared statements
$stmt = $db->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);

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

// Handle the results as needed
$result = $stmt->get_result();
// ...rest of the code