How can the issue of losing values when trying to write to the database be resolved in the PHP script?

Issue: The problem of losing values when trying to write to the database in a PHP script can be resolved by properly sanitizing and validating user input before inserting it into the database. This can prevent any unexpected characters or SQL injections from causing data loss.

// Sanitize and validate user input before writing to the database
$name = mysqli_real_escape_string($conn, $_POST['name']);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);

// Insert sanitized data into the database
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if(mysqli_query($conn, $sql)){
    echo "Record added successfully.";
} else{
    echo "Error: " . mysqli_error($conn);
}