How can PHP be used to validate user input before saving it to a database?

When saving user input to a database, it is important to validate the data to ensure it meets the necessary criteria and is safe to store. PHP can be used to perform validation checks on user input before saving it to the database. This can include checking for the correct data type, length, format, and any other specific requirements.

// Example code to validate user input before saving it to a database
$user_input = $_POST['user_input'];

// Check if input is not empty
if (!empty($user_input)) {
    // Perform additional validation checks here
    // For example, check if input is a valid email address
    if (filter_var($user_input, FILTER_VALIDATE_EMAIL)) {
        // Save the validated user input to the database
        // $db->query("INSERT INTO table_name (column_name) VALUES ('$user_input')");
        echo 'User input is valid and saved to the database.';
    } else {
        echo 'Invalid email address.';
    }
} else {
    echo 'User input cannot be empty.';
}