bloggincodin bloggincodin - 1 year ago 52
MySQL Question

PHP MySQL form validation

i'm currently working on a project with php and mysql. I'm very new to PHP and I want to be able to check the form for errors before the form action is completed. (The form action is sending information to mySQL database).

if(isset($_POST['SendOrder'])) {

$FirstName1Err = $LastName1Err = $Email1Err = $Phone1Err = $productsErr = $Size1Err = $Quantity1Err = $Price1Err = "";

if (empty($_POST['FirstName1'])) {
$FirstName1Err = "Your first name is required"; }

if (empty($_POST['LastName1'])) {
$LastName1Err = "Your last name is required"; }

if (empty($_POST['Email1'])) {
$Email1Err = "Your email is required"; }

if (empty($_POST['Phone1'])) {
$Phone1Err = "Your phone number is required"; }

if (empty($_POST['products'])) {
$productsErr = "Choosing a product is required"; }

if (empty($_POST['Size1'])) {
$Size1Err = "Choosing a size is required"; }

if (empty($_POST['Quantity1'])) {
$Quantity1Err = "Choosing a quantity is required"; }

if (empty($_POST['Price1'])) {
$Price1Err = "Choosing a price is required"; }


require 'NFTconnect2.php';



$FirstName1 = $_POST['FirstName1'];
$LastName1 = $_POST['LastName1'];
$Email1 = $_POST['Email1'];
$Phone1 = $_POST['Phone1'];
$products = $_POST['products'];
$Size1 = $_POST['Size1'];
$Quantity1 = $_POST['Quantity1'];
$Price1 = $_POST['Price1'];

$a_sql=mysqli_query($con, "INSERT INTO Inventory VALUES('','$FirstName1','$LastName1', '$Email1', '$Phone1', '$products', '$Size1', '$Quantity1', '$Price1')");

$msg='Your order was successful!';
$msg= 'Your order was not successful! ';


Basically my question is: How can I write an "if" statement so that I can check the form for validations first and then if the validations pass, then I can run the second part of the code. Thanks in advance

Answer Source

Add a variable at the beginning called $hasError = false;

For each line you add an error, set $hasError = true; like this:

if (empty($_POST['FirstName1'])) { 
$FirstName1Err = "Your first name is required"; 
$hasError = true;} 

if (empty($_POST['LastName1'])) { 
$LastName1Err = "Your last name is required"; 
$hasError = true;} 


Then, wrap the second part of your code in an if like so:

if (!$hasError) {  //If hasError is still false
  //Do stuff

I do feel obliged to mention that there are much more efficient ways of validating each field, though this was not your concern nor your question, so I'll leave my answer as is :)