How can PHP be used to validate user input from HTML forms before executing MySQL queries to prevent errors or security vulnerabilities?

To validate user input from HTML forms before executing MySQL queries in PHP, you can use functions like `filter_input()` or `htmlspecialchars()` to sanitize input and prevent SQL injection attacks. Additionally, you can use regular expressions or specific validation functions to ensure the data meets the expected format or criteria.

// Example of validating user input from an HTML form before executing MySQL queries

// Retrieve user input from form
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);

// Validate input
if (!$username || !$email) {
    echo "Invalid input. Please try again.";
} else {
    // Proceed with MySQL query
    $query = "INSERT INTO users (username, email) VALUES ('$username', '$email')";
    // Execute query
}