I wonder if you can help me please. I am passing data from a html form into a MySQL DB using PHP. All fields have been validated but I want it to validate all the data before any of it goes into the DB.
For example, if there are not enough characters entered in the ‘name’ field it will tell the user, however if the email address is correctly validated it then inserts the data into the DB. How would I go about doing that?
// check the length of 'name' field if between 2 and 50 characters
if ((strlen($name) < 2 || strlen($name) > 50)) {
echo "The name is invalid, must be between 2 and 50 chearacters.";
exit;
}
echo "</br>";
// check field name contains numbers
if (preg_match('#[0-9]#',$name)){
echo 'The name is invalid, its contains numbers. Please go back and try again.';
}
echo "</br>";
// Check if email is valid. If not tell the user it is invalid
$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
if (!preg_match($regex, $emailaddress)) {
echo "Invalid email address. Please go back and try again.";
}
// insert the data from the registration form into the DB
mysql_query("INSERT into customers
(cs_name, cs_emailaddress)
VALUES
(
'".$name."', '".$emailaddress."',
)
")
or die(mysql_error());
You make the script die before mysql_query() is called, or you create a $isValid variable initially true that you set to false when something goes wrong. And you put a condition before mysql_query: