I am validating a form data using this script below.
When i submit the form if there is any errors the error message is displaying properly but if no errors and validation succeed i try to echo out the variables to test the script but the script is only displaying this : []
Please examine the code and help me solve this.
<?php
//included files
include("./includes/connect.php");
include("./includes/functions.php");
$errors = array();
//checking if user have submitted the form
if(isset($_POST['submitted'])) {
//validating and cleaning submitted form data ...
if (isset($_POST['name']) && !empty($_POST['name'])) {
if(preg_match("/^[a-zA-Z ]{2,20}$/", strip_trim($_POST['name']))) {
$cln_name = clean_data($_POST['name']);
} else {
$_POST['name'] = FALSE;
$errors[] = "The name you entered is not valid";
}
} else {
$errors[] = "You have not enter your name!";
}
if(isset($_POST['email']) && !empty($_POST['email'])) {
$cln_email = filter_var($_POST['email'] , FILTER_SANITIZE_EMAIL);
if(filter_var($cln_email, FILTER_VALIDATE_EMAIL)) {
$cln_email = clean_data($cln_email);
} else {
$_POST['email'] = FALSE;
$errors[] = "The email you entered is not valid";
}
} else {
$errors[] = "You have not provide you email!";
}
if(isset($_POST['plate_num']) && !empty($_POST['plate_num'])) {
if(ctype_alnum($_POST['plate_num']) && strlen($_POST['plate_num']) >= 5) {
$cln_plate_num = clean_data($_POST['plate_num']);
} else {
$_POST['plate_num'] = FALSE;
$errors[] = "The plate number you provided is not a valid plate number";
}
} else {
$errors[]= "You have not provide a plate number";
}
//checking for errors and printing errors..
if (count($errors > 0)) {
$errors_to_json = json_encode($errors);
echo $errors_to_json;
//foreach ($errors as $error) {
//echo $error . "<br />";
//}
} else {
echo $cln_name . "<br />";
echo $cln_email . "<br />";
echo $cln_plate_num;
}
} else {
echo "You did not submit the form!";
}
?>
This script is returning only this :
[]
Any idea please ??
functions.php :
<?php
function clean_data($data) {
if(function_exists('mysql_real_escape_string')) {
global $dbc;
$data = mysql_real_escape_string(trim($data), $dbc);
$data = strip_tags($data);
} else {
$data = mysql_escape_string(trim($data));
$data = strip_tags($data);
}
return $data;
}
function strip_trim($data) {
$data = stripslashes(trim($data));
return $data;
}
?>
you have problem in your if condition:
//checking for errors and printing errors..
if (count($errors > 0)) {
...
this will always return to TRUE because $error = [] and count([] > 0) results to TRUE
that's why you always end up in:
$errors_to_json = json_encode($errors);
echo $errors_to_json;
// Will indeed display '[]' because json_encode([]) is '[]'
i believe what you mean here is:
if (count($errors) > 0) {
...
Related
I am new in php. My form is working properly but its show successful message even when it is empty and submitted.
How to show an error message when the form is submitted empty?
Here is the code :
if(empty($_POST['submit']) === false) {
$email = htmlentities(strip_tags($_POST['email']));
$logname = 'email.txt';
$logcontents = file_get_contents($logname);
if(strpos($logcontents,$email)) {
die('You are already subscribed.');
} else {
$filecontents = $email.', ';
$fileopen = fopen($logname,'a+');
$filewrite = fwrite($fileopen,$filecontents);
$fileclose = fclose($fileopen);
if(!$fileopen or !$filewrite or !$fileclose or '') {
die('Error occured');
} else {
echo 'Your email has been added.';
}
}
} else {
showForm();
}
Thank you
Well this is easy, you should have found it yourself ;-)
I added a check for empty eMail field, and then show an errorMessage and the form again.
if(empty($_POST['submit']) === false) {
if(empty($_POST['email'])) {
echo 'Please enter an email to add in the email field!';
showForm();
} else {
$email = htmlentities(strip_tags($_POST['email']));
$logname = 'email.txt';
$logcontents = file_get_contents($logname);
if(strpos($logcontents,$email)) {
die('You are already subscribed.');
} else {
$filecontents = $email.', ';
$fileopen = fopen($logname,'a+');
$filewrite = fwrite($fileopen,$filecontents);
$fileclose = fclose($fileopen);
if(!$fileopen or !$filewrite or !$fileclose or '') {
die('Error occured');
} else {
echo 'Your email has been added.';
}
}
}
} else {
showForm();
}
Right now, posting a snippet of what I wrote:
if (isset($_POST["email1"] != $_POST["email2"])) {
$email2Err = "please enter the same email address";
}
Every single time when I try to post the snippet above or a variation of it, it literally blanks out my page.
Question is, is the code I wrote above a good way to compare two email addresses via text fields?
And why does it blank out my entire page every time?
Here's a bit of further context if that's more helpful (let me know you want the entire page):
<?php
session_start(); //allows use of session variables
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["nights"])) {
$nightsErr = "# of nights are required";
} else {
$nights = test_input($_POST["nights"]);
}
if (empty($_POST["arrivals"])) {
$arrivalsErr = "Time of arrival is required";
} else {
$arrivals = test_input($_POST["arrivals"]);
}
if (empty($_POST["male"])) {
$maleErr = "# of people (gender female) required";
} else {
$male = test_input($_POST["male"]);
}
if (empty($_POST["female"])) {
$femaleErr = "# of people (gender female) required";
} else {
$female = test_input($_POST["female"]);
}
if (empty($_POST["rooms"])) {
$roomsErr = "# of rooms required";
} else {
$rooms = test_input($_POST["rooms"]);
}
if (empty($_POST["type"])) {
$typeErr = "type of rooms required";
} else {
$type = test_input($_POST["type"]);
}
if (empty($_POST["name"])) {
$nameErr = "name required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["address"])) {
$addressErr = "address required";
} else {
$address = test_input($_POST["address"]);
}
if (empty($_POST["zip"])) {
$zipErr = "zip required";
} else {
$zip = test_input($_POST["zip"]);
}
if (empty($_POST["telephone"])) {
$telephoneErr = "telephone required";
} else {
$telephone = test_input($_POST["telephone"]);
}
if (empty($_POST["email1"])) {
$email1Err = "email required";
} else {
$email1 = test_input($_POST["email1"]);
}
if (empty($_POST["email2"])) {
$email2Err = "email2 required";
} else {
$email2 = test_input($_POST["email2"]);
}
if (isset($_POST["email1"] != $_POST["email2"])) {
$email2Err = "please enter the same email address";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
This is failing you and isn't the right syntax for what you want to achieve:
if (isset($_POST["email1"] != $_POST["email2"]))
What you need to do is to first check if it is set then check if both are (not) equal to, but it's best to use !empty(), then check if it is not equal to:
if (!empty($_POST["email1"]) && !empty($_POST["email2"])) {
if ($_POST["email1"] != $_POST["email2"]) {
$email2Err = "Emails don't match. Please enter the same email address.";
}
}
Plus, make sure your form elements both have the right name attributes.
Also, a blank page can mean syntax errors.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
What you are doing is assigning by using a single equals to sign rather make it a double equals to sign, I mean ==
Try:
if (isset($_POST["email1"]) && isset($_POST["email2"])) {
if ($_POST["email1"] != $_POST["email2"]) {
$email2Err = "please enter the same email address";
}
}
I'm trying to familiarize myself with PHP by making a simple pizza ordering system that emails size, toppings, and the orderer's information. The email sends nicely, but the toppings section of the email is blank. What am I missing?
Thanks!
<?php
/* Set e-mail recipient */
$myemail = "katrina.skovan#gmail.com";
$subject = "Pizza Order";
/* Check all form inputs using check_input function */
$name = check_input($_POST['name'], "Enter your name");
$email = check_input($_POST['email'], "Enter your email");
$street = check_input($_POST['street'], "Enter your your street");
$apt = check_input($_POST['apt'], "Enter your your apartment number");
$zip = check_input($_POST['zip'], "Enter your ZIP code");
$phone = check_input($_POST['phone'], "Enter your phone number");
$comments = $_POST['comments'];
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("E-mail address not valid");
}
/* the following code is currently not working */
$pepperoni = $_POST['pepperoni'];
if(isset($_POST['pepperoni']) &&
$_POST['Pepperoni'] == 'Yes')
{
echo "pepperoni";
}
else
{
echo "";
}
if(isset($_POST['Half Pepperoni']) &&
$_POST['halfpepperoni'] == 'Yes')
{
echo "halfpepperoni";
}
else
{
echo "";
}
if(isset($_POST['Onions']) &&
$_POST['onions'] == 'Yes')
{
echo "onions";
}
else
{
echo "";
}
if(isset($_POST['Half Onions']) &&
$_POST['halfonions'] == 'Yes')
{
echo "halfonions";
}
else
{
echo "";
}
if(isset($_POST['Mushrooms']) &&
$_POST['mushrooms'] == 'Yes')
{
echo "mushrooms";
}
else
{
echo "";
}
if(isset($_POST['Half Mushrooms']) &&
$_POST['halfmushrooms'] == 'Yes')
{
echo "halfmushrooms";
}
else
{
echo "";
}
if(isset($_POST['Peppers']) &&
$_POST['peppers'] == 'Yes')
{
echo "peppers";
}
else
{
echo "";
}
if(isset($_POST['Half Peppers']) &&
$_POST['halfpeppers'] == 'Yes')
{
echo "halfpeppers";
}
else
{
echo "";
}
if(isset($_POST['Extra Cheese']) &&
$_POST['extracheese'] == 'Yes')
{
echo "extracheese";
}
else
{
echo "";
}
if(isset($_POST['Half Extra Cheese']) &&
$_POST['halfextracheese'] == 'Yes')
{
echo "halfextracheese";
}
else
{
echo "";
}
if(isset($_POST['Sausage']) &&
$_POST['sausage'] == 'Yes')
{
echo "sausage";
}
else
{
echo "";
}
if(isset($_POST['Half Sausage']) &&
$_POST['halfsausage'] == 'Yes')
{
echo "halfsausage";
}
else
{
echo "";
}
/* Let's prepare the message for the e-mail */
/* -=-=-=- EDITED -=-=-=- The toppings should be uncommented BUT you need to make variables like above Likewise the checkboxes need to have associated.
here's annother example variable:
$pepperoni = $_POST['pepperoni'];
*/
$message = "
Toppings:
$pepperoni
$halfpepperoni
$onions
$halfonions
$mushrooms
$halfmushrooms
$peppers
$halfpeppers
$extracheese
$halfextracheese
$sausage
$halfsausage
Name: $name
Email: $email
Street: $street
Apt: $apt
ZIP: $zip
Phone: $phone
Comments: $comments
";
$headers = "From:" . $email;
/* Send the message using mail() function */
/*mail($name, $email, $apt, $zip, $phone, $comments $pepperoni $halfpepperoni $onions $halfonions $mushrooms $halfmushrooms $peppers $halfpeppers $extracheese $halfextracheese $sausage $halfsausage);*/
mail($myemail,$subject,$message,$headers);
/* Redirect visitor to the thank you page */
header('Location: thanks.html');
exit();
/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<html>
<body>
<p>Please correct the following error:</p>
<strong><?php echo $myError; ?></strong>
<p>Hit the back button and try again</p>
</body>
</html>
<?php
exit();
}
?>
Replace all space between the textfield name, Ex: use halfonions instead of using textname with space like Half Onions
if(isset($_POST['halfonions']) && $_POST['halfonions'] == 'Yes') {
instead of
if(isset($_POST['Half Onions']) && $_POST['halfonions'] == 'Yes') {
You are not setting your variables, you are only echoing them out:
/* the following code is currently not working */
$pepperoni = $_POST['pepperoni'];
if(isset($_POST['pepperoni']) &&
$_POST['Pepperoni'] == 'Yes')
{
echo "pepperoni";
}
else
{
echo "";
}
Now the $pepperoni variable will contain Yes if it was selected and nothing else. And that is the only variable you are currently trying to set, the rest of the variables in your message is undefined.
You probably want something like:
if(isset($_POST['pepperoni']) &&
$_POST['pepperoni'] == 'Yes')
{
$pepperoni = "pepperoni";
}
else
{
$pepperoni = "";
}
And that for all the variables you use in your message.
And you can reduce that to:
$pepperoni = isset($_POST['pepperoni']) ? 'pepperoni' : '';
^ or however it is spelled in the html...
as the value does not really matter.
I think there are spaces in the variables like "Half Pepperoni" or "Half Mushrooms" !!
Js fiddle to have a look into form:http://jsfiddle.net/aBp34/
The form working finely ,it's just that I'm unable to insert any data into the database.
Surprisingly there's no error generated!
*ERROR:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''name','nric','hp','gender','occupation','ins_orga','events','size')VALUES(kalai' at line 1*
Below is the mysqli commands in php:
Any help would be appreciated :)
<?php
if(isset($_POST['submitted']))
{
if(empty($_POST['name']))
{
$name=NULL;
echo'Please fill up your name!'.'</br>';
}
else
//to check name(char only)
if(!empty($_POST['name']))
{
$name=$_POST['name'];
$pattern='/([[:alpha:]]|[[:space:]])/';
if(!preg_match($pattern, $name))//slighly silly but it echo only if preg_match mismatch
{
echo 'Please key in a valid name!'.'</br>';
}
}
// to check NRIC(only numbers and size=12)
if(empty($_POST['nric']))
{
$nric=NULL;
echo'Please key in your NRIC!'.'</br>';
}
else
if(!empty($_POST['nric']))
{
$nric=$_POST['nric'];
$pattern='/[0-9]{12}/';
if(!preg_match($pattern, $nric))
{
echo 'Please key in a valid NRIC number!'.'</br>';
}
}
//to check h/p number
if(empty($_POST['hp']))
{
$hp=NULL;
echo'Please key in your H/P Number!'.'</br>';
}
else
if(!empty($_POST['hp']))
{
$hp=$_POST['hp'];
$pattern='/(\\d{10})/';
if(!preg_match($pattern, $hp))
{
echo 'Please key in a valid Mobile number!'.'</br>';
}
}
//to check email
if(empty($_POST['email']))
{
$email=NULL;
echo'Please key in your email id!';
}
else
if(!empty($_POST['email']))
{
$hp=$_POST['email'];
$pattern='/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!"?(?>\\\[ -~]|[^"]){65,}"?#)(?>([!#-\'*+\/-9=?^-~-]+)(?>\.(?1))*|"(?>[ !#-\[\]-~]|\\\[ -~])*")#(?!.*[^.]{64,})(?>([a-z\d](?>[a-z\d-]*[a-z\d])?)(?>\.(?2)){0,126}|\[(?:(?>IPv6:(?>([a-f\d]{1,4})(?>:(?3)){7}|(?!(?:.*[a-f\d][:\]]){8,})((?3)(?>:(?3)){0,6})?::(?4)?))|(?>(?>IPv6:(?>(?3)(?>:(?3)){5}:|(?!(?:.*[a-f\d]:){6,})(?5)?::(?>((?3)(?>:(?3)){0,4}):)?))?(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)(?>\.(?6)){3}))\])$/iD';
if(!preg_match($pattern, $hp))
{
echo 'Please key in a valid email id!'.'</br>';
}
}
//to check gender
if(!isset($_POST['gender']))
{
$gender=NULL;
echo"Kindly select your gender!".'</br>';
}
else
{
$gender=$_POST['gender'];
}
//to check occupation
if(!isset($_POST['occupation']))
{
$occupation=NULL;
echo"Kindly select your occupation!".'</br>';
}
else
{
$occupation=$_POST['occupation'];
if(empty($_POST['ins_orga']))
{
echo'Please name your institution or organization!';
}
else
{
$ins_orga=$_POST['ins_orga'];
}
}
//to check events
if(!empty($_POST['events']))
{
$events = $_POST['events'];
}
if(!isset($events))
{
echo("<p>You didn't select any events!</p>\n").'</br>';
}
else
{
$nevents = count($events);
echo"You selected ".$nevents ."events: ".'</br>';
for($i=0; $i < $nevents; $i++)
{
echo($events[$i] . " ");
}
}
if(empty($_POST['size']))
{
echo"please select your size".'</br>';
}
else
{
$size=$_POST['size'];
echo $size;
}
if(isset($_POST['area']))
{
$area=$_POST['area'];
}
if(isset($_POST['captain_code']))
{
$captain_code=$_POST['captain_code'];
}
if(isset($_POST['address']))
{
$address=$_POST['address'];
}
if(isset($_POST['s1']))
{
$s1=$_POST['s1'];
}
// check all
if('$name'&&'$nric'&&'$hp'&&'$email'&&'$gender'&&'$occupation'&&'$events'&&'$size')
{
echo "you have successfully registered! Your code is: ";
// set uniqid
$order_id = uniqid(rand(10,1000),false);
$order_id = substr($order_id,rand(0,strlen($order_id) - 4),4);
echo hexdec($order_id);
$mysqli=new mysqli('localhost','root','','volunteer-registration');
if(mysqli_connect_errno())
{
echo 'Connection failed', mysql_connect_error();
exit();
}
$insert="INSERT INTO volunteer_registration(name,nric,hp,email_id,address,gender,occupation,ins_orga,events,size,area,s1,captain_code)VALUES($name,$nric,$hp,$email,$address,$gender,$occupation,$ins_orga,$events,$size,$area,$s1,$captain_code)";
$query= mysqli_query($mysqli, $insert)or die(mysqli_error($mysqli));
}
}
?>
With the issues pointed by others following code snippet
$row=$result->fetch_fields();
foreach($result as $val)
{
///
}
I think it should be
$row=$result->fetch_fields();
foreach($row as $val)
{
///
}
First issue I see:
if('$name'&&'$nric'&&'$hp'&&'$email'&&'$gender'&&'$occupation'&&'$events'&&'$size')
should be
if (isset($name, $nric, $hp, $email, $gender, $occupation, $events, $size))
The way you are doing it now you are just seeing if the string literal '$name' is truthy - which it always will be, since you aren't checking the variable $name.
Next issue is that you never do an insert into the database, just a select.
Edit: with your insert, you have
$insert="INSERT INTO volunteer_registration(...)VALUES($name,$nric, ... , $captain_code)
You need to put quotes around the values:
$insert="INSERT INTO volunteer_registration(...)VALUES('$name','$nric', ... ,'$captain_code')
I just fix your validation, and for the sql code is up to you
maybe you can try to make it more simple...
<?php
if (isset($_POST['submitted'])) {
$msg = "";
$name = $_POST['name'];
$pattern='/([[:alpha:]]|[[:space:]])/';
if (empty($name)) {
$msg .= "<li>Please fill up your name!</li>";
}
if (!preg_match($pattern, $name)) {
$msg .= "<li>Please key in a valid name!</li>";
}
if (empty($_POST['nric'])) {
$msg .= "<li>Please key in your NRIC!</li>";
}
if (!is_numeric($_POST['nric'])) {
$msg .= "<li>Please key in a valid NRIC number!</li>";
}
if (empty($_POST['hp'])) {
$msg .= "<li>Please key in your H/P Number!</li>";
}
if (!is_numeric($_POST['nric']) && $_POST['nric'] < 10) {
$msg .= "<li>Please key in a valid Mobile number!</li>";
}
if (empty($_POST['email'])) {
$msg .= "<li>Please key in your email id!</li>";
}
if ((!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$_POST['email']))) {
$msg .= "<li>Please key in a valid email id!</li>";
}
if (empty($_POST['gender'])) {
$msg .= "<li>Kindly select your gender!</li>";
}
if (empty($_POST['occupation'])) {
$msg .= "<li>Kindly select your occupation!</li>";
}else{
$occupation=$_POST['occupation'];
if(empty($_POST['ins_orga'])) {
$msg .= "<li>Please name your institution or organization!</li>";
}else{
$ins_orga=$_POST['ins_orga'];
}
}
if (empty($_POST['events'])) {
$msg .= "<li>You didn't select any events!</li>";
}
else{
$nevents = count($events);
# ...
}
if(empty($_POST['size'])) {
$msg .= "<li>please select your size!</li>";
}
if ($msg=="") {
$order_id = uniqid(rand(10,1000),false);
$order_id = substr($order_id,rand(0,strlen($order_id) - 4),4);
$code = hexdec($order_id);
$msg .= "you have successfully registered! Your code is: ".$code."";
# Your code SQL...
# ......
#......
}
}
?>
<?php echo $msg; ?>
This is function is taking up a lot of lines on my Functions page.
I can't figure out on how to take it down unless putting them into an array, then using a foreach loop. But I want it to be specific on what is not allowed to be blank.
if ($EmployeeID === "")
{
echo "EmployeeID Is Blank.";
}
else
{
if ($Firstname === "")
{
echo "Firstname Is Blank.";
}
else
{
if ($Lastname === "")
{
echo "Last Name Is Blank";
}
else
{
if ($PhoneNumber === "")
{
echo "Phone Number Is Blank";
}
else
{
if ($Address === "")
{
echo "Address Is Blank";
}
else
{
if ($City === "")
{
echo "City Is Blank";
}
else
{
if ($State === "")
{
echo "Sate Is Blank";
}
else
{
if ($Zip === "")
{
echo "Zip Is Blank";
}
else
{
if ($Email === "")
{
echo "Email Is Blank";
}
else
{
if ($Password === "")
{
echo "Password Is Blank";
}
else
{
echo "All Success";
}
}
}
}
}
}
}
}
}
}
The Solution I have Found which takes the lines down, but doesn't give me the exact on what field is left empty is:
$Array = array();
$Array[] = $EmpID;
$Array[] = $FirstName;
$Array[] = $Lastname;
$Array[] = $PhoneNumber;
$Array[] = $Address;
$Array[] = $City;
$Array[] = $State;
$Array[] = $Zip;
$Array[] = $Email;
$Array[] = $Password;
foreach ($Array AS $Checking)
{
if (empty($Checking))
{
echo "One Or More Is Left Blank";
exit;
}
}
try{
if(empty($EmployeeID)){
throw new Exception('EmployeeID Is Blank.');
}elseif(empty($Firstname)){
throw new Exception('Firstname Is Blank.');
}elseif(empty($Lastname)){
throw new Exception('Lastname Is Blank.');
}elseif(empty($PhoneNumber)){
throw new Exception('PhoneNumber Is Blank.');
}elseif(empty($Address)){
throw new Exception('Address Is Blank.');
}elseif(empty($City)){
throw new Exception('City Is Blank.');
}elseif(empty($State)){
throw new Exception('State Is Blank.');
}elseif(empty($Zip)){
throw new Exception('Zip Is Blank.');
}elseif(empty($Email)){
throw new Exception('Email Is Blank.');
}elseif(empty($Password)){
throw new Exception('Password Is Blank.');
}
echo 'All Success';
}catch(Exception $e){
echo $e->getMessage();
}
Maybe you can reorganize it like this:
$messages = array();
if (empty($EmployeeID)){
$messages[] = "EmployeeID Is Blank.";
}
if (empty($Firstname)){
$messages[] = "Firstname Is Blank.";
}
// and so on for the rest.
At the end you can check if $messages is empty to validate:
if (empty($messages)){
echo "All Success";
}else {
echo "Errors:";
foreach($messages as $message){
echo "$message <br>";
}
}
Why are you using al these else statements? I would present all errors all at once to avoid messing with the user (the user fixes the error and then all of a sudden another pops up...).
An easy example:
echo empty($EmployeeID) ? 'EmployeeID Is Blank.' : '';
echo empty($Firstname) ? 'Firstname Is Blank.' : '';
//etc.
I would probably add all error messages to an array and loop through that / check if it is empty:
$errors = array();
if (empty($EmployeeID))
{
$errors['employeeid'] = 'EmployeeID Is Blank.';
}
if (empty($Firstname))
{
$errors['firstname'] = 'Firstname Is Blank.';
}
// etc.
if (count($errors) > 0)
{
// error handling
}
// and you can use the array keys to display the appropriate messages at the appropriate place if it is set:
if (isset($errors['employeeid']))
{
// display the EmployeeID error message where the field should be filled in
}
You could use an associative array like this:
$formValues = array(
'Employee ID' => $EmployeeID,
'First Name' => $Firstname,
'Last Name'=> $Lastname,
'Phone Number'=> $PhoneNumber,
'Address'=> $Address,
'City'=> $City,
'State'=> $State,
'Zip'=> $Zip,
'Email'=> $Email,
'Password'=> $Password,
);
$error=false;
foreach ($formValues as $key => $value) {
if(empty($value)) {
echo($key.' is blank');
$error=true;
}
}
if(!$error) {
echo("All Success");
}
Wrap it all up in a form validator:
<?php
function is_form_valid() {
if ($Firstname === "") { return false; }
if ($Lastname === "") { return false; }
// ...
return true;
}
?>
Of course, this only highlights the idea and you will need to determine the best method for passing in your form fields. Then use that as a single call in your main processing routine:
<?php
if (is_form_valid()) {
// do stuff
} else {
// report error
}
?>
To make it more useful, you can create a shared class for valid input in name fields, emails, etc and call that from your form validation. Imagining such a class exists, your method would look like:
<?php
function is_form_valid() {
if (! $validator->is_valid_name($Firstname)) { return false; }
if (! $validator->is_valid_name($Lastname)) { return false; }
if (! $validator->is_valid_email($Email)) { return false; }
if (! $validator->is_valid_phone($Phone)) { return false; }
// ...
return true;
}
?>
Just be aware of the many regional differences regarding names, phone numbers, addresses, etc. You can read about common pitfalls here. There are also several questions on this forum about the subject of data validation.
Most of the other answers are better, but you should also learn to use elseif():
if ($EmployeeID === "") {
echo "EmployeeID Is Blank.";
} elseif ($Firstname === "") {
echo "Firstname Is Blank.";
} elseif ($Lastname === "") {
echo "Last Name Is Blank";
} //etc
$errors = "";
if($EmployeeID == "")
{
$errors .= "Employee ID blank<br />";
}
if($Firstname == "")
{
$errors .= "First Name blank<br />";
}
if($errors != "")
{
echo $errors;
}