What are the best practices for validating user input in PHP forms before writing to a database?

Validating user input in PHP forms before writing to a database is crucial to ensure data integrity and prevent security vulnerabilities such as SQL injection attacks. It is recommended to use server-side validation techniques such as filtering input, sanitizing data, and validating against predefined rules. This can be achieved by using PHP functions like filter_var() and preg_match().

// Example of validating user input in a PHP form before writing to a database

// Retrieve user input from a form
$username = $_POST['username'];
$email = $_POST['email'];

// Validate the input using filter_var() and preg_match()
if (filter_var($email, FILTER_VALIDATE_EMAIL) && preg_match("/^[a-zA-Z0-9]*$/", $username)) {
    // Input is valid, proceed to write to the database
    // Insert the data into the database using prepared statements to prevent SQL injection
} else {
    // Input is not valid, display an error message to the user
    echo "Invalid input. Please enter a valid username and email address.";
}