The assignment is to create an html form where the user enters the required information, and process the form data via PHP to display the output using $_post method. I can't seem to get the output right, it just basically displays the php code that I wrote. any insight is greatly appreciated
Note: The html code is lengthy, but I'm sure it's correct. My problem is with the PHP(next) code.
the following is the output:
0){ $Name = trim($_POST['name']); $adr = trim($_POST['address']); $City = trim($_POST['city']); $state = trim($_POST['state']); $zip = trim($_POST['zip']); $phone = trim($_POST['phone']); $email = trim($_POST['email']); $err = array(); if($Name == ''){ $err[] = "Please enter your name"; } if($adr == ''){ $err[] = "Please enter your address"; } if($City == ''){ $err[] = "Please enter your city"; } if($state == ''){ $err[] = "Please enter your State"; } if($zip == ''){ $err[] = "Please enter your zip"; } if($phone == ''){ $err[] = "Please enter your phone number"; } if($email == ''){ $err[] = "Please enter your email"; } if(count($err) > 0){ foreach($err as $value){ echo"$value
"; } echo " Go Back"; } else{ //header("Location:HTMLform.html"); echo "Name: " . $_POST["name"]; echo "Address: " . $_POST["address"] ; echo "City: " . $_POST["city"] ; echo "State: " . $_POST["state"]; echo "Zip: " . $_POST["zip"]; echo "Phone: " . $_POST["phone"]; echo "Email: " . $_POST["email"]; } } ?>
page 1 (HTML FORM)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "
http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Coffee Order</title>
</head>
<body><h1>The Coffee House</h1>
<div>
<div><h3>Order Form</h3></div>
<form name='frmInput' action="process.php" method="post">
<table><tr><td>Coffee:</td>
<td><select name="coffeeCode" id="Coffee">
<option value="">Select Coffee:</option><option value="bv">Boca Villa ($7.99/lb)
</option>
<option value="sbr">South Beach Rhythm ($8.99/lb)</option>
<option value="pp">Pumpkin Paradise ($8.99/lb)</option>
<option value="ss">Sumatran Sunset ($9.99/lb)</option>
<option value="bb">Bali Batur ($10.95/lb)</option>
<option value="dd">Double Dark ($9.95/lb)</option></select></td></tr>
<tr><td>
Type:</td>
<td>
<input type="radio" name="coffeeType" value="caf">Regular<br/>
<input type="radio" name="coffeeType" value="decaf">Decaffeinated
</td>
</tr>
<tr>
<td>Quantity (in pounds):</td>
<td>
<input type="text" name="quantity" maxlength="3" size="3" id="Quantity">
</td>
</tr>
<tr>
<td>Name:</td>
<td>
<input type="text" name="name" id="Name">
</td>
</tr>
<tr>
<td>E-mail address:</td>
<td>
<input type="text" name="email" id="Email">
</td>
</tr>
<tr>
<td>Telephone #:</td>
<td>
<input type="text" name="phone" maxlength="14" size="14" id="Telephone">
</td>
</tr>
<tr>
<td>Address:</td>
<td>
<input type="text" name="address" id="Address">
</td>
</tr>
<tr>
<td>City:</td>
<td>
<input type="text" name="city" id="City">
</td>
</tr>
<tr>
<td>State:</td>
<td>
<input type="text" name="state" maxlength="2" size="2"
style="text-transform: uppercase" id="State">
</td>
</tr>
<tr>
<td>Zip:</td>
<td>
<input type="text" name="zip" maxlength="10" size="10" id="Zip">
</td>
</tr>
<tr>
<td><input type="submit" value="Submit"></td><td><input type="reset"></td>
</tr>
</table>
</form></div></body>
</html>
php code:
<?php
if (count($_POST) > 0){
$Name = trim($_POST['name']);
$adr = trim($_POST['address']);
$City = trim($_POST['city']);
$state = trim($_POST['state']);
$zip = trim($_POST['zip']);
$phone = trim($_POST['phone']);
$email = trim($_POST['email']);
$err = array();
if($Name == ''){
$err[] = "Please enter your name";
}
if($adr == ''){
$err[] = "Please enter your address";
}
if($City == ''){
$err[] = "Please enter your city";
}
if($state == ''){
$err[] = "Please enter your State";
}
if($zip == ''){
$err[] = "Please enter your zip";
}
if($phone == ''){
$err[] = "Please enter your phone number";
}
if($email == ''){
$err[] = "Please enter your email";
}
if(count($err) > 0){
foreach($err as $value){
echo"$value<br/>";
}
echo "<a href='HTMLform.html'> Go Back</a>";
}
else{
//header("Location:HTMLform.html");
echo "Name: " . $_POST["name"];
echo "Address: " . $_POST["address"] ;
echo "City: " . $_POST["city"] ;
echo "State: " . $_POST["state"];
echo "Zip: " . $_POST["zip"];
echo "Phone: " . $_POST["phone"];
echo "Email: " . $_POST["email"];
}
}
?>
You have some errors in your code.
There is a space between <? tag and php in line 1. Remove that
There is no closing curly brace for this , if (count($_POST) > 0) {. Add a closing curly brace before the ending ?> tag.
You have the name field of telephone set to 'phone'.
So find all lines having this
$_POST['telephone']
and change it to
$_POST['phone']
Also, If you want to see the results, comment out
header('Location:HTMLForm.html');
PHP file are saved with .php extension and has an opening of
PHP code should be at the top of the page, before any HTML tag
Instead of using $variable == '' to check if it's empty, use function called empty($variable) that return true if empty
You are doing a redirect in the first line of the else statement, so the rest of the code won't be executed, therefore the echo part will never be reached. Put this header("Location:HTMLform.html"); as the last statement in the else scope
old
// is this suppose to be an array?
$err = array();
if($_POST['name'] == null){
array_push($err,'error stuff stuff stuff');
}
print_r($err);
// if not array
$err = '';
if($_POST['name'] == null){
$err.= 'error stuff stuff stuff';
}
Also, What are you trimming from the post?
Related
I am trying to create a PHP validation FORM.
Validation errors are displaying correctly for me every time. My only problems is that I am not able to set the focus on the input with error if an error came.
For example, I am using $rut_error, $first_name_error, $last_name_error, $email_error, $address_error and I want to set focus on the corresponding input if any error came.
I tried using javascript but I am not cleared where should I put that code, Could anyone guide me how to solve it? Can I fix this only with PHP? Please help.
I tried entering here but no success:
//First name Validation
if (empty($_POST["first_name"]) and $rut_error == '')
{
$first_name_error = "First name is required";
echo "<script>document.registration.first_name.focus();</script>";
}
My code is below:
addStudent.php
<html>
<head>
<title>Add Client</title>
</head>
<body>
Show Client
<?php include('form_processStudent.php'); ?>
<div id="divAgenda">
<form id="contact" action="<?= htmlspecialchars($_SERVER["PHP_SELF"]) ?>" method="post" name = "registration">
<fieldset>
<span class="error"><?= $rut_error ?></span><br>
<input placeholder="Rut..." id="rut" type="text" name="rut" value="<?= $rut ?>" tabindex="1" size="8" maxlength="8"> - <input type="text" name="dv" value="<?= $dv ?>" size="1" tabindex="2" maxlength="1"> Ejemplo: 12345678-1<br>
</fieldset>
<fieldset>
<span class="error"><?= $first_name_error ?></span><br>
<input placeholder="Primer Nombre..." id="first_name" type="text" id="first_name" name="first_name" value="<?= $first_name ?>" maxlength="50" tabindex="3"><br>
</fieldset>
<fieldset>
<span class="error"><?= $last_name_error ?></span><br>
<input placeholder="Segundo Nombre..." id="last_name" type="text" id="last_name" name="last_name" value="<?= $last_name ?>" maxlength="50" tabindex="4"><br>
</fieldset>
<fieldset>
<span class="error"><?= $email_error ?></span><br>
<input placeholder="Correo Electrónico..." id="email" type="text" name="email" value="<?= $email ?>" maxlength="100" tabindex="5"><br>
</fieldset>
<fieldset>
<span class="error"><?= $address_error ?></span><br>
<input placeholder="Dirección..." id="address" type="text" name="address" value="<?= $address ?>" maxlength="200" tabindex="5"><br>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Enviar</button>
</fieldset>
</form>
</body>
</html>
form_processStudent.php
<?php
// define variables and set to empty values
echo"<script>
document.registration.last_name.focus();
return false;
</script>";
$rut_error = $first_name_error = $last_name_error = $email_error = $address_error = "";
$rut = $dv = $first_name = $last_name = $email = $address = "";
if(isset($_POST['submit']))
{
//RUT Validation
$rut = test_input($_POST["rut"]);
$dv = ($_POST["dv"]);
if ( empty($_POST["rut"]))
{
$rut_error = "RUT is required";
}
else if ( $dv=='' )
{
$rut_error = "Verification digit is required";
}
else if (!is_numeric($rut))
{
$rut_error = "Entered RUT is not numeric";
}
else if (!((strlen($rut) == 7) or (strlen($rut) == 8)))
{
$rut_error = "Number of digits of RUT not valid";
}
else
{
$x = 2; $s = 0; $dv2 = 0;
for($i = (strlen($rut) - 1); $i >= 0; $i--)
{
if($x > 7)
$x = 2;
$s += ($rut[$i] * $x);
$x++;
}
$dv2=11-($s % 11);
if($dv2 == 10)
$dv2 = 'K';
if($dv2 == 11)
$dv2 = '0';
if($dv2 == $dv)
{
//echo "<br>". "rut={" . $rut . "}";
//echo "<br>". "dv ={" . $dv . "}";
}
else
$rut_error = "invalid RUT";
}
//First name Validation
if (empty($_POST["first_name"]) and $rut_error == '')
{
$first_name_error = "First name is required";
echo "<script>document.registration.first_name.focus();</script>";
}
else
{
if ($rut_error == '')
{
$first_name = test_input($_POST["first_name"]);
//echo "<br>". "first_name={" . $first_name . "}";
}
}
//Last name Validation
if (empty($_POST["last_name"]) and $rut_error == '' and $first_name_error == '')
{
$last_name_error = "Second name is required";
echo "<script>function validateform()
{
document.registration.last_name.focus();
return false;
}
</script>";
}
else
{
if ($rut_error == '' and $first_name_error == '')
{
$last_name = test_input($_POST["last_name"]);
//echo "<br>". "last_name={" . $last_name . "}";
}
}
//Email Validation
if (empty($_POST["email"]) and $rut_error == '' and $first_name_error == '' and $last_name_error == '')
{
$email_error = "Email is required";
}
else
{
if ($rut_error == '' and $first_name_error == '' and $last_name_error == '')
{
$email = test_input($_POST["email"]);
//echo "<br>". "email={" . $email . "}";
// check if e-mail address is well-formed
if ((!filter_var($email, FILTER_VALIDATE_EMAIL)) and $rut_error == '' and $first_name_error == '' and $last_name_error == '')
{
$email_error = "Invalid email";
}
}
}
//Adress Validation
if (empty($_POST["address"]) and $rut_error == '' and $first_name_error == '' and $last_name_error == '' and $email_error == '')
{
$address_error = "Address is required";
}
else
{
if ($rut_error == '' and $first_name_error == '' and $last_name_error == '' and $email_error == '')
{
$address = test_input($_POST["address"]);
//echo "<br>". "address={" . $address . "}";
}
}
if ($rut_error == '' and $first_name_error == '' and $last_name_error == '' and $email_error == '' and $address_error == '')
{
//echo "<br>". "Dentro de IF";echo "<br>";
require_once('mysqli_connect.php');
$query = "INSERT INTO students (rut, dv, first_name, last_name, email, address) VALUES (?,?,?,?,?,?)";
$stmt = mysqli_prepare($dbc, $query);
mysqli_stmt_bind_param($stmt, "ssssss", $rut, $dv, $first_name, $last_name, $email, $address);
mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
echo 'affected_rows=<' . $affected_rows . '>';
if($affected_rows == 1)
{
$rut = $dv = $first_name = $last_name = $email = $address = '';
echo "<br>"."Client Entered";
mysqli_stmt_close($stmt);
mysqli_close($dbc);
}
else
{
echo 'Error Occurred<br />';
echo mysqli_error();
mysqli_stmt_close($stmt);
mysqli_close($dbc);
}
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
getStudentInfo.php
Add Client
<?php
// Get a connection for the database
require_once('mysqli_connect.php');
// Create a query for the database
$query = "SELECT serie, rut, dv, first_name, last_name, email, address FROM students ORDER BY serie desc";
// Get a response from the database by sending the connection
// and the query
$response = #mysqli_query($dbc, $query);
// If the query executed properly proceed
if($response)
{
echo '<table align="left" cellspacing="5" cellpadding="8">
<tr><td align="left"><b>Serie </b></td>
<td align="left"><b>Rut </b></td>
<td align="left"><b>Dígito Verificador </b></td>
<td align="left"><b>Primer Nombre </b></td>
<td align="left"><b>Segundo Nombre </b></td>
<td align="left"><b>Email </b></td>
<td align="left"><b>Dirección </b></td>
</tr>';
// mysqli_fetch_array will return a row of data from the query
// until no further data is available
while($row = mysqli_fetch_array($response))
{
echo '<tr><td align="left">' . $row['serie'] . '</td>
<td align="left">' . $row['rut'] . '</td>
<td align="left">' . $row['dv'] . '</dv>
<td align="left">' . $row['first_name'] . '</td>
<td align="left">' . $row['last_name'] . '</td>
<td align="left">' . $row['email'] . '</td>
<td align="left">' . $row['address'] . '</td>'
;
echo '</tr>';
}
echo '</table>';
}
else
{
echo "Couldn't issue database query<br />";
echo mysqli_error($dbc);
}
// Close connection to the database
mysqli_close($dbc);
?>
mysqli_connect.php
<?php
// Defined as constants so that they can't be changed
DEFINE ('DB_USER', 'studentweb');
DEFINE ('DB_PASSWORD', '123');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'dbTest');
// $dbc will contain a resource link to the database
// # keeps the error from showing in the browser
$dbc = #mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die('Could not connect to MySQL: ' . mysqli_connect_error());
//echo "Connected...\n\n";
?>
You can do it via javascript.
You put a script that would work once the page is fully loaded.
The script will checkout the content of each <span class="error">. If some non empty one is found, it shall put the focus on it.
In your html:
<body>
...
<script type="text/javascript">
window.onload = function(){
var errors = document.querySelectorAll('.error');
for(var i = 0, l = errors.length; i < l; i++){
var error = errors[i],
shouldForcus = error.textContent.trim().length !== 0;
if(shouldFocus){
var input = error.parentNode.querySelector('input');
input.focus();
break;
}
}
}
</script>
</body>
I know the tag form has an attribute called action and I know how action works, this is how I used it
<form method="post" action = "registerd.php">
</form>
The registerd.php page also exists as well.
Now I am doing some validation in the tag form using php validation, but why does it jump to the registerd.php page without validating the values at first?
is there any other solutions to this rather than using the header at the end of php code like :
header("location : registerd.php")
here is the whole code I'm writing
Thank you very much in advance
<div id = "content">
<?php
$fnameErr = "";
$lnameErr = "";
$idErr = "";
$placeErr = "";
$dateErr = "";
$emailErr = "";
$pswErr = "";
$file;
$content = "";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(isset($_POST['register'])){
if(isset($_POST['firstname'])){
if(!empty($_POST['firstname'])){
if(strlen($_POST['firstname'])>1){
if(preg_match("/[a-zA-Z]+/", $_POST['firstname'])==1){
$firstname = test_input($_POST['firstname']);
$content .= "firstname:";
$content .= $firstname;
$content .= " ";
}
else{
$fnameErr = "your first name should only include letters";
}
}
else{
$fnameErr = "your first name must be at least 2 characters";
}
}
else{
$fnameErr = "enter your first name";
}
}
else{
$fnameErr = "enter your first name";
}
if(isset($_POST['lastname'])){
if(!empty($_POST['lastname'])){
if(strlen($_POST['lastname'])>3){
if(preg_match("/[a-zA-Z]+/", $_POST['lastname'])==1){
$lastname = test_input($_POST['lastname']);
$content .= "lastname:";
$content .= $lastname;
$content .= " ";
}
else{
$lnameErr = "your last name should only include letters";
}
}
else{
$lnameErr = "your last name must be at least 2 characters";
}
}
else{
$lnameErr = "enter your last name";
}
}
else{
$lnameErr = "enter your last name";
}
if(isset($_POST['idnum'])){
if(!empty($_POST['idnum'])){
if(strlen($_POST['idnum'])==10){
if(preg_match("/[0-9]{10}/", $_POST['idnum'])==1){
$idnum = test_input($_POST['idnum']);
$content .= "ID_No.:";
$content .= $idnum;
$content .= " ";
}
else{
$idErr = "your ID number should only include digits";
}
}
else{
$idErr = "your ID number must be 10 digits";
}
}
else{
$idErr = "enter your ID number";
}
}
else{
$idErr = "enter your ID number";
}
if(isset($_POST['placeOfBirth'])){
if(!empty($_POST['placeOfBirth'])){
if(strlen($_POST['placeOfBirth'])>2){
if(preg_match("/[a-zA-Z]+/", $_POST['placeOfBirth'])==1){
$placeOfBirth = test_input($_POST['placeOfBirth']);
$content .= "placeOfBirth:";
$content .= $placeOfBirth;
$content .= " ";
}
else{
$placeErr = "your place of birth should only include digits";
}
}
else{
$placeErr = "your place of birth must be at least 3 letters";
}
}
}
if(isset($_POST['date'])){
if(!empty($_POST['date'])){
$date = test_input($_POST['date']);
$content .= "date:";
$content .= $date;
$content .= " ";
}
else{
$dateErr = "enter your date of birth";
}
}
else{
$dateErr = "enter your date of birth";
}
if(isset($_POST['email'])){
if(!empty($_POST['email'])){
$email = test_input($_POST['email']);
$content .= "email:";
$content .= $email;
$content .= " ";
}
else{
$emailErr = "enter your email";
}
}
else{
$emailErr = "enter your email";
}
if(isset($_POST['password'])){
if(!empty($_POST['password'])){
if(preg_match("/(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$/", $_POST['password'])==1){
$password = test_input($_POST['password']);
$content .= "password:";
$content .= $password;
$content .= " ";
}
else{
$pswErr = "your password should have numbers, uppercase<br/> & lowercase letters";
}
}
else{
$pswErr = "enter your password";
}
}
else{
$pswErr = "enter your password";
}
if(file_exists($email.".txt")){
echo(
"<script>
alert('this email already exists!');
</script>"
);
$firstname = $lastname = $idnum = $date = $placeOfBirth = $password = "";
}
else{
$file = fopen($email.".txt","a+") or die("Unable to open file!");
fwrite($file, $content);
fclose($file);
header("location: registered.php");
}
}
?>
<fieldset id = "fieldset">
<legend><h1 class = "reg" >Register Form</h1></legend>
<form method="post" action="#" enctype = "multipart/form-data">
<table class = "table">
<tr>
<td class = "labels">
<p class = "star">*</p> First Name
</td>
<td><input class = "inclass" type="text" required="required" placeholder="Please enter your first name" id = "firstname" name="firstname" onclick = "colorBorder(this.id)"/></td>
</tr>
<td class = "err">
<span>
<?php
echo $fnameErr;
?>
</span>
</td>
<tr>
<td class = "labels"><p class = "star">*</p> Last Name</td>
<td><input class = "inclass" type="text" required="required" placeholder="Please enter your last name" name="lastname" id = "lastname" onclick = "colorBorder(this.id)"/></td>
</tr>
<td class = "err">
<span>
<?php
echo $lnameErr;
?>
</span>
</td>
<tr>
<td class = "labels">Gender</td>
<td>
<input class = "inclass" type="radio" name="gender" value="0" /><p class = "radio" >Male</p>
<input class = "inclass" type="radio" name="gender" value="1" /><p class = "radio" >Female</p>
</td>
</tr>
<tr>
<td class = "labels"><p class = "star">*</p> ID Number</td>
<td><input class = "inclass" type="text" id="idnum" required="required" placeholder="Please enter your ID number" name="idnum" onclick = "colorBorder(this.id)"/></td>
</tr>
<td class = "err">
<span>
<?php
echo $idErr;
?>
</span>
</td>
<tr>
<td class = "labels">Place of Birth</td>
<td><input class = "inclass" type="text" placeholder="Please enter your place of birth" name="placeOfBirth" id = "place" onclick = "colorBorder(this.id)"/></td>
</tr>
<td class = "err">
<span>
<?php
echo $placeErr;
?>
</span>
</td>
<tr>
<td class = "labels"><p class = "star">*</p> Date Of Birth</td>
<td><input class = "inclass" type="date" id = "date" name="date"/></td>
</tr>
<td class = "err">
<span>
<?php
echo $dateErr;
?>
</span>
</td>
<tr>
<td class = "labels"><p class = "star">*</p> Email</td>
<td><input class = "inclass" type="email" required="required" placeholder="Please enter your email" name="email" id = "email" onclick = "colorBorder(this.id)"/></td>
</tr>
<td class = "err">
<span>
<?php
echo $emailErr;
?>
</span>
</td>
<tr>
<td class = "labels"><p class = "star">*</p> Passwords</td>
<td><input class = "inclass" type="password" required="required" placeholder="Please enter your password" name="password" id = "password" onclick = "colorBorder(this.id)"/></td>
</tr>
<td class = "err">
<span>
<?php
echo $pswErr;
?>
</span>
</td>
<tr>
<td><input type="submit" name="register" value="register" class="save"/></td>
<td><input type="reset" name = "reset" id = "reset"/></td>
</tr>
</table>
</form>
</fieldset>
</div>
write down your php validation code on register.php and if value are not validate than redirect to ur form page using header function.
header("location : form.php")
I believe the solution to your problem is to separate your code, the HTML in one file ("form.php"), the PHP validation in another file ("validate.php") :
"form.php" will collect the data, the "action" of the form will execute "validate.php".
"validate.php" will validate the data, if no error found it will "header" to "registered.php", if error found it will store the message in $_SESSION and "header" back to "form.php", where the message will be displayed.
Example :
form.php
<?php
session_start(); // NECESSARY TO USE $_SESSION.
?>
<html>
<body>
<form action="validate.php" method="post">
Enter 0 or 1 : <input type="text" name="num"/>
<br/>
<input type="submit" value="Submit"/>
</form>
<?php
// CHECK IF THERE IS ERROR MESSAGE FROM VALIDATION.
if ( isset( $_SESSION[ "err_msg" ] ) )
{ echo $_SESSION[ "err_msg" ];
unset( $_SESSION[ "err_msg" ] ); // VERY IMPORTANT : DESTROY ERROR MESSAGE.
}
?>
</body>
</html>
validate.php
<?php
session_start(); // NECESSARY TO USE $_SESSION.
if ( isset( $_POST[ "num" ] ) ) // IF CALLED FROM "FORM.PHP"
{ $num = $_POST[ "num" ];
if ( ( $num == "0" ) || ( $num == "1" ) ) // VALIDATE NUMBER.
header( "Location: registered.php" ); // NO ERROR.
else { $_SESSION[ "err_msg" ] = "Number must be 0 or 1."; // MESSAGE.
header( "Location: form.php" ); // ERROR.
}
}
else header( "Location: form.php" ); // WASN'T CALLED FROM "FORM.PHP".
?>
Create two files with the given names and copy-paste previous codes, then run "form.php".
You will have to paste all your huge validation in "validate.php". Your validation has many messages, I recommend you to insert one "header" after each message and add "exit" immediately after (because "header" does not stop the execution of the script).
The approach adopted below bypasses the superfluous use of isset. This also means that the checking for all $_POST['data'] Variables where consolidated unto one section of the Code, right after checking if the Submit Button-Value was set. The Function function test_input($data) {...} was completely removed since the Section mentioned above also does exactly the same thing... Multiline String-Concatenation was condensed to one single Line for brevity... There seemed also to be some extraneous if(){...}else{...} clauses all over the place. Those were ignored since they might serve some purpose to the Original Poster (though unlikely). Finally, to ensure that the form is posted back to the Current, Executing Script (considering that the processing of the Form Data is in the same Script); we would leave the action Attribute of the Form EMPTY: meaning that the Form would automatically post back to itself - the current Script.
<?php
// AT THE VERY TOP OF THE SCRIPT - PREFERABLY NOT WITHIN A DIV OR ANY CONTAINER, START YOUR PHP CODES...
$fnameErr = "";
$lnameErr = "";
$idErr = "";
$placeErr = "";
$dateErr = "";
$emailErr = "";
$pswErr = "";
$content = "";
$file;
if(isset($_POST['register'])){
// GATHER A FILTERED VERSION OF THE POST VARIABLES:
$firstName = isset($_POST['firstname']) ? htmlspecialchars(stripslashes(trim($_POST['firstname']))) : null;
$lastName = isset($_POST['lastname']) ? htmlspecialchars(stripslashes(trim($_POST['lastname']))) : null;
$idNum = isset($_POST['idnum']) ? htmlspecialchars(stripslashes(trim($_POST['idnum']))) : null;
$placeOfBirth = isset($_POST['placeOfBirth']) ? htmlspecialchars(stripslashes(trim($_POST['placeOfBirth']))) : null;
$date = isset($_POST['date']) ? htmlspecialchars(stripslashes(trim($_POST['date']))) : null;
$email = isset($_POST['email']) ? htmlspecialchars(stripslashes(trim($_POST['email']))) : null;
$password = isset($_POST['password']) ? htmlspecialchars(stripslashes(trim($_POST['password']))) : null;
if($firstName){
if(!empty($firstName)){
if(strlen($firstName)>1){
if(preg_match("/[a-zA-Z]+/", $firstName)==1){
$content .= "firstname:" . $firstName . " ";
}
else{
$fnameErr = "Your first name should only include letters";
}
}
else{
$fnameErr = "Your first name must be at least 2 characters";
}
}
else{
$fnameErr = "Enter your first name";
}
}else{
$fnameErr = "Enter your first name";
}
if(isset($lastName)){
if(!empty($lastName)){
if(strlen($lastName)>3){
if(preg_match("/[a-zA-Z]+/", $_POST['lastname'])==1){
$content .= "lastname:" . $lastName . " ";
}
else{
$lnameErr = "Your last name should only include letters";
}
}
else{
$lnameErr = "Your last name must be at least 2 characters";
}
}
else{
$lnameErr = "Enter your last name";
}
}else{
$lnameErr = "Enter your last name";
}
if(isset($idNum)){
if(!empty($idNum)){
if(strlen($idNum) == 10){
if(preg_match("/[0-9]{10}/", $_POST['idnum'])==1){
$content .= "ID_No.:" . $idNum . " ";
}
else{
$idErr = "Your ID number should only include digits";
}
}
else{
$idErr = "Your ID number must be 10 digits";
}
}
else{
$idErr = "Enter your ID number";
}
}else{
$idErr = "Enter your ID number";
}
if(isset($placeOfBirth)){
if(!empty($placeOfBirth)){
if(strlen($placeOfBirth)>2){
if(preg_match("/[a-zA-Z]+/", $placeOfBirth)==1){
$content .= "placeOfBirth:" . $placeOfBirth . " ";
}
else{
$placeErr = "Your place of birth should only include digits";
}
}else{
$placeErr = "Your place of birth must be at least 3 letters";
}
}
}
if(isset($date)){
if(!empty($date)){
$content .= "date:" . $date . " ";
}else{
$dateErr = "Enter your date of birth";
}
}else{
$dateErr = "Enter your date of birth";
}
if(isset($email)){
if(!empty($email)){
$content .= "email:" . $email . " ";
}else{
$emailErr = "Enter your email";
}
}else{
$emailErr = "Enter your email";
}
if(isset($password)){
if(!empty($password)){
if(preg_match("/(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$/", $password)==1){
$content .= "password:" . $password . " ";
}else{
$pswErr = "Your password should have numbers, uppercase<br/> & lowercase letters";
}
}else{
$pswErr = "Enter your password";
}
}else{
$pswErr = "Enter your password";
}
if(file_exists($email.".txt")){
echo "<script type='text/javascript'>alert('this email already exists!');</script>";
$firstname = $lastname = $idnum = $date = $placeOfBirth = $password = "";
}
else{
$file = fopen($email.".txt","a+") or die("Unable to open file!");
fwrite($file, $content);
fclose($file);
header("location: registered.php");
}
}
?>
<div id = "content">
<fieldset id = "fieldset">
<legend><h1 class = "reg" >Register Form</h1></legend>
<!-- SINCE YOUR VALIDATION IS IN THE CURRENT SCRIPT, LEAVING THE action ATTRIBUTE EMPTY IMPLIES THAT THE FORM WILL POST BACK TO ITSELF [THE CURRENT SCRIPT]. -->
<form method="POST" action="" enctype = "multipart/form-data">
<table class = "table">
<tr>
<td class = "labels">
<p class = "star">*</p> First Name
</td>
<td>
<input class = "inclass" type="text" required="required" placeholder="Please enter your first name" id = "firstname" name="firstname" onclick = "colorBorder(this.id)"/>
</td>
<td class = "err">
<span><?php echo $fnameErr; ?></span>
</td>
</tr>
<tr>
<td class = "labels"><p class = "star">*</p> Last Name</td>
<td>
<input class = "inclass" type="text" required="required" placeholder="Please enter your last name" name="lastname" id = "lastname" onclick = "colorBorder(this.id)"/>
</td>
<td class = "err">
<span><?php echo $lnameErr; ?></span>
</td>
</tr>
<tr>
<td class = "labels">Gender</td>
<td>
<input class = "inclass" type="radio" name="gender" value="0" /><p class = "radio" >Male</p>
<input class = "inclass" type="radio" name="gender" value="1" /><p class = "radio" >Female</p>
</td>
</tr>
<tr>
<td class = "labels"><p class = "star">*</p> ID Number</td>
<td>
<input class = "inclass" type="text" id="idnum" required="required" placeholder="Please enter your ID number" name="idnum" onclick = "colorBorder(this.id)"/>
</td>
<td class = "err">
<span><?php echo $idErr; ?></span>
</td>
</tr>
<tr>
<td class = "labels">Place of Birth</td>
<td>
<input class = "inclass" type="text" placeholder="Please enter your place of birth" name="placeOfBirth" id = "place" onclick = "colorBorder(this.id)"/>
</td>
<td class = "err">
<span><?php echo $placeErr; ?></span>
</td>
</tr>
<tr>
<td class = "labels"><p class = "star">*</p> Date Of Birth</td>
<td>
<input class = "inclass" type="date" id = "date" name="date"/>
</td>
<td class = "err">
<span><?php echo $dateErr; ?></span>
</td>
</tr>
<tr>
<td class = "labels"><p class = "star">*</p> Email</td>
<td>
<input class = "inclass" type="email" required="required" placeholder="Please enter your email" name="email" id = "email" onclick = "colorBorder(this.id)"/>
</td>
<td class = "err">
<span><?php echo $emailErr; ?></span>
</td>
</tr>
<tr>
<td class = "labels"><p class = "star">*</p> Passwords</td>
<td>
<input class = "inclass" type="password" required="required" placeholder="Please enter your password" name="password" id = "password" onclick = "colorBorder(this.id)"/>
</td>
<td class = "err">
<span><?php echo $pswErr; ?></span>
</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="register" value="register" class="save"/></td>
<td><input type="reset" name = "reset" id = "reset"/></td>
</tr>
</table>
</form>
</fieldset>
</div>
I am trying to insert form field values after validating the form.
I develope a seperate php file validate1.php to insert the form field values in database and another file describing form and its validation is in connection.php
When I run connection.php, form fields are getting validated only once,and after form is submitted after that i enter anything.Which should not be happened.
My connection.php is
<html>
<head>
<title></title>
<style> .error {color:#ff0000;} </style>
</head>
<body>
<?php
$companyNameErr = $addressErr = $emailErr = $contactErr = "";
$companyName = $address = $email = $contact = $description = "";
function test_data($data)
{
$data=trim($data);
$data=stripslashes($data);
$data=htmlspecialchars($data);
return $data;
}
$errors = array();
if ( $_SERVER["REQUEST_METHOD"] =="POST" )
{
$companyName=$_POST["companyName"];
if( empty($companyName) )
{
$companyNameErr = "Please Enter Company Name";
$errors[]= $companyNameErr ;
}
else
{
if( !preg_match("/^[a-zA-Z ]*$/",$companyName) )
{
$companyNameErr = "Invalid Company Name";
$errors[]= $companyNameErr ;
}
else
{
$companyName=test_data($companyName);
}
}
$address=$_POST["address"];
if( empty($address) )
{
$addressErr = "Please Enter Address";
$errors[]= $addressErr ;
}
else
{
$address=test_data($address);
}
$email=$_POST["email"];
if( empty($email) )
{
$emailErr = "Please Enter Email";
$errors[]= $emailErr ;
}
else
{
if( !filter_var($email, FILTER_VALIDATE_EMAIL) )
{
$emailErr = "Invalid Email";
$errors[]= $emailErr ;
}
else
{
$email=test_data($email);
}
}
$contact=$_POST["contact"];
if( empty($contact) )
{
$contactErr = "Please Enter Contact Number";
$errors[]= $contactErr ;
}
else
{
if( !preg_match("/^[0-9]*$/",$contact ) )
{
$contactErr = "Invalid Contact";
$errors[]= $contactErr ;
}
else
{
$contact=test_data($contact);
}
}
}
?>
<form name="myform" method="post" action="<?php if(empty($errors)){ echo $_SERVER["PHP_SELF"]; }else{ echo "validate1.php"; }?>" >
<table>
<tr>
<td>Company Name</td>
<td><input type="text" name="companyName" value ="<?php if(isset($_POST['companyName']) && empty($companyNameErr)){ echo $_POST['companyName'];} else {echo '';}?>" required ><span class="error"><sup>*</sup><?php echo $companyNameErr; ?></span></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address" value ="<?php if(isset($_POST['address']) && empty($addressErr)){ echo $_POST['address'];} else {echo '';}?>" required><span class="error"><sup>*</sup><?php echo $addressErr; ?></span></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" value ="<?php if(isset($_POST['email']) && empty($emailErr)){ echo $_POST['email'];} else {echo '';}?>" required><span class="error"><sup>*</sup><?php echo $emailErr; ?></span></td>
</tr>
<tr>
<td>Contact</td>
<td>+91-<input type="text" name="contact" value ="<?php if(isset($_POST['contact']) && empty($contactErr)){ echo $_POST['contact'];} else {echo '';}?>" required maxlength="10" minlength="10"><span class="error"><sup>*</sup><?php echo $contactErr; ?></span></td>
</tr>
<tr>
<td>Description</td>
<td><textarea name="description" cols="60" rows="3"></textarea></td>
</tr>
</table>
<input type="submit" name="submit" value="submit">
</form>
</body>
and Validate1.php is
<html>
<head>
<title></title>
</head>
<body>
<?php
$servername="localhost";
$username="root";
$password="";
$conn = new mysqli($servername, $username, $password, 'mydatabase');
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$conn->query("CREATE DATABASE IF NOT EXISTS `MyDataBase`");
$conn->query("CREATE TABLE IF NOT EXISTS MyDataBase.company_details( `comp_id` INT AUTO_INCREMENT PRIMARY KEY,`company_name` VARCHAR(50) NOT NULL,`address` VARCHAR(70) NOT NULL,`email` VARCHAR(30) NOT NULL,`contact` INT(13) NOT NULL,`description` VARCHAR(150))");
$conn->query("INSERT INTO company_details (company_name, address, email, contact, description ) VALUES ( '".$_POST['companyName']."', '".$_POST['address']."', '".$_POST['email']."', '".$_POST['contact']."', '".$_POST['description']."')");
$conn->close();
?>
</body>
Try the following code
N:B : Make sure you have used sql injection prevention techniques when posting form data.
connection.php
<?php
session_start();
$companyName = $address = $email = $contact = $description = "";
function test_data($data)
{
$data=trim($data);
$data=stripslashes($data);
$data=htmlspecialchars($data);
return $data;
}
$_SESSION['error'] = array();
$_SESSION['resend'] = array();
if ( $_SERVER["REQUEST_METHOD"] =="POST")
{
$companyName=$_POST["companyName"];
if(empty($companyName) )
$_SESSION['error']['companyNameErr'] = "Please Enter Company Name";
else
{
if( !preg_match("/^[a-zA-Z ]*$/",$companyName) )
$_SESSION['error']['companyNameErr'] = "Invalid Company Name";
else
$_SESSION['resend']['companyName'] = test_data($companyName);
}
$address=$_POST["address"];
if(empty($address) )
$_SESSION['error']['addressErr'] = "Please Enter Address";
else
$_SESSION['resend']['address'] = test_data($address);
$email=$_POST["email"];
if(empty($email))
$_SESSION['error']['emailErr'] = "Please Enter Email";
else
{
if( !filter_var($email, FILTER_VALIDATE_EMAIL) )
$_SESSION['error']['emailErr'] = "Invalid Email";
else
$_SESSION['resend']['email'] = test_data($email);
}
$contact=$_POST["contact"];
if(empty($contact))
$_SESSION['error']['contactErr'] = "Please Enter Contact Number";
else
{
if( !preg_match("/^[0-9]*$/",$contact ) )
$_SESSION['error']['contactErr'] = "Invalid Contact";
else
$_SESSION['resend']['contact'] = test_data($contact);
}
$description=$_POST["description"];
$_SESSION['resend']['description'] = test_data($description);
if(empty($_SESSION['error'])){
header('location:validate1.php');
exit;
}
}
?>
<html>
<head>
<title></title>
<style> .error {color:#ff0000;} </style>
</head>
<body>
<form name="myform" method="post" action="<?php echo $_SERVER["PHP_SELF"];?>" >
<table>
<tr>
<td>Company Name</td>
<td><input type="text" name="companyName" value ="<?php if(isset($_SESSION['resend']['companyName']) && empty($_SESSION['error']['companyNameErr'])){ echo $_SESSION['resend']['companyName'];} else {echo '';}?>" required ><span class="error"><sup>*</sup><?php if(isset($_SESSION['error']['companyNameErr'])) echo $_SESSION['error']['companyNameErr']; ?></span></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address" value ="<?php if(isset($_SESSION['resend']['address']) && empty($_SESSION['error']['addressErr'])){ echo $_SESSION['resend']['address'];} else {echo '';}?>" required><span class="error"><sup>*</sup><?php if(isset($_SESSION['error']['addressErr'])) echo $_SESSION['error']['addressErr']; ?></span></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" value ="<?php if(isset($_SESSION['resend']['email']) && empty($_SESSION['error']['emailErr'])){ echo $_SESSION['resend']['email'];} else {echo '';}?>" required><span class="error"><sup>*</sup><?php if(isset($_SESSION['error']['emailErr'])) echo $_SESSION['error']['emailErr']; ?></span></td>
</tr>
<tr>
<td>Contact</td>
<td>+91-<input type="text" name="contact" value ="<?php if(isset($_SESSION['resend']['contact']) && empty($_SESSION['error']['contactErr'])){ echo $_SESSION['resend']['contact'];} else {echo '';}?>" required maxlength="10" minlength="10"><span class="error"><sup>*</sup><?php if(isset($_SESSION['error']['contactErr'])) echo $_SESSION['error']['contactErr']; ?></span></td>
</tr>
<tr>
<td>Description</td>
<td><textarea name="description" cols="60" rows="3"><?php if(isset($_SESSION['resend']['description'])) echo $_SESSION['resend']['description'];?></textarea></td>
</tr>
</table>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
Validate1.php
<?php
session_start();
if(isset($_SESSION['resend'])){
$servername="localhost";
$username="root";
$password="";
$conn = new mysqli($servername, $username, $password, 'test');
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
//$conn->query("CREATE DATABASE IF NOT EXISTS `MyDataBase`");
$conn->query("CREATE TABLE IF NOT EXISTS test.company_details( `comp_id` INT AUTO_INCREMENT PRIMARY KEY,`company_name` VARCHAR(50) NOT NULL,`address` VARCHAR(70) NOT NULL,`email` VARCHAR(30) NOT NULL,`contact` INT(13) NOT NULL,`description` VARCHAR(150))");
$result = $conn->query("INSERT INTO company_details (company_name, address, email, contact, description ) VALUES ( '".$_SESSION['resend']['companyName']."', '".$_SESSION['resend']['address']."', '".$_SESSION['resend']['email']."', '".$_SESSION['resend']['contact']."', '".$_SESSION['resend']['description']."')");
$conn->close();
unset ($_SESSION['resend']);
unset ($_SESSION['error']);
header('location:connection.php');
exit;
}
?>
<html>
<head>
<title></title>
</head>
<body>
</body>
</html>
Hi please excuse the rookie question as I am still very much learning PHP. Im trying to do a basic form validation. Im trying to get any errors found upon validation to be displayed in red inside the form field.
how to add login form validation errors inside the login form the error msg is not coming inside the loginform
<form action="test.php" method="POST" >
<div class="logintable ">
<table class="applyfont" style="border: 1px solid lightseagreen">
<tbody>
<tr id="login1">
<td class="applyfontbold"><b>Login </b></td>
</tr>
<tr>
<td style="padding-right:10px;">
<input type="text" name="name" value="" placeholder="Username or Email" id="uname">
<span class="error">* <?php echo $nameErr;?></span>
</td>
</tr>
<tr>
<td>
<input type="password" name="password" value="" placeholder="Password" id="password">
<span class="error">* <?php echo $passeErr;?></span>
</td>
</tr>
<tr>
<td>
<p class="submit"><input type="submit" name="save" value="Submit"> </p>
</td>
</tr>
<tr>
<td>
<div class="login-help applyfontlighter">
<p>Forgot your password? <span id="footer"><u style="color:red;">Click here to reset it.</u></span></p>
</div>
<p id="new"><button type="button" class="btn btn-default btn-xs" >New Registers</button></p>
</td>
</tr>
</tbody>
</table>
</div>
</form>
<?php
$nameErr = "";
$passErr = "";
$x = "typepass";
if (isset($_POST['save'])) {
if (empty($_POST['name'])) {
$nameErr .= "Name is required";
} else {
$name = $_POST['name'];
}
if (empty($_POST['password'])) {
$passeErr .= "password is required";
} elseif ($_POST['password'] !== $x) {
$passeErr .= "password doesn't match";
} else {
$password = $_POST['password'];
}
echo "Username :" . " " . $name . "<br>" . "Password :" . " " . $password;
}
?>
With your current code you are setting 2 vars when there are errors:
$passeErr
$nameErr
You could add a new html tag inside your login form like
<span class="error"></span>
And inside this span you can use php to see if the vars are set. If they are you display them. if they are not you do nothing like so:
You use isset for this. In your example you try to echo the errors all the time. Even when they are not set before logging in. This will produce warnings.
error for password
<span class="error">
if(isset($passeErr)){
echo $passeErr;
}
</span>
error for name
<span class="error">
if(isset($nameErr)){
echo $nameErr;
}
</span>
Now make sure you do your form validation above the form and it should work!
<?php
$x = "typepass";
if (isset(trim($_POST['save']))) {
if (empty($_POST['name'])) {
$nameErr = "Name is required";
} else {
$name = $_POST['name'];
}
if (empty(trim($_POST['password']))) {
$passeErr = "password is required";
} elseif ($_POST['password'] !== $x) {
$passeErr = "password doesn't match";
} else {
$password = $_POST['password'];
}
if(isset($nameErr)||(isset($passErr)))
{
echo $nameErr . "<br>" .$passErr;
}
else // no error
{
echo "Username :" . " " . $name . "<br>" . "Password :" . " " . $password;
}
}
?>
I have separate email script; however, how would we run that code if there are no errors. I have a array with form errors $errors = array($nameErr, $emailErr, $phoneErr, $zipErr, $serviceErr); but they have different strings, if there are no strings or Null or '' inside the array, we would like to send email.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $phoneErr = $emailErr = $zipErr = $serviceErr = "";
$name = $phone = $email = $zip = $service = $comment = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "name required.";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "letters and spaces only.";
}
}
if (empty($_POST["email"])) {
$emailErr = "email required.";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "invalid email format.";
}
}
if (empty($_POST["phone"])) {
$phoneErr = "phone required.";
} else {
//Check phone for numbers () or - only
$phone = test_input($_POST["phone"]);
if (!preg_match("/^[\+0-9\-\(\)\s]*$/", $phone)) {
$phoneErr = "format.";
}
}
if (empty($_POST["zip"])) {
$zipErr = "zip required.";
} else {
$zip = test_input($_POST["zip"]);
}
if (!preg_match("/^[\+0-9\-\(\)\s]*$/", $zip)){
$zipErr = "format.";
}
if ($_POST["service"] == NULL ) {
$serviceErr = "service required.";
}else {
$service = test_input($_POST["service"]);
}
$comment = test_input($_POST["comment"]);
//**********************************************************************
$errors = array($nameErr, $emailErr, $phoneErr, $zipErr, $serviceErr);
if (isset($_POST['Submit'])) {
//if no errors run send email CODE.
}
//***********************************************************************
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
<td> Name:
<br />
<input name="name" type="text" size="20" value="<?php echo $name;?>">
<span class="error">* <?php echo "<br />"; echo $nameErr;?></span>
</td>
</tr>
<tr>
<td> Phone:
<br />
<input name="phone" type="text" size="20" value="<?php echo $phone;?>">
<span class="error">* <?php echo "<br />"; echo $phoneErr;?></span>
</td>
</tr>
<tr>
<td> E-mail:
<br />
<input name="email" type="text" size="20" value="<?php echo $email;?>">
<span class="error">* <?php echo "<br />"; echo $emailErr;?></span>
</td>
</tr>
<tr>
<td> Zip:
<br />
<input name="zip" type="text" size="20" value="<?php echo $zip;?>">
<span class="error">* <?php echo "<br />"; echo $zipErr;?></span>
</td>
</tr>
<tr>
<td> Service:
<br />
<select name="service">
<option selected="selected" value="<?php echo $service;?>"><?php echo $service;?></option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
<span class="error">* <?php echo "<br />"; echo $serviceErr;?></span>
</td>
</tr>
<tr>
<td> Message:
<br />
<textarea name="comment" rows="2" cols="20"><?php echo $comment;?></textarea></td>
</tr>
<tr>
<td>
<input type="submit" name="Submit" value="Send" />
</td>
</tr>
</table>
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $phone;
echo "<br>";
echo $zip;
echo "<br>";
echo $service;
echo "<br>";
echo "$comment";
?>
</body>
</html>
try with the below code:
$errors = array($nameErr, $emailErr, $phoneErr, $zipErr, $serviceErr);
if (isset($_POST['Submit'])) {
if(!array_filter($errors)){
// code here
}
else {
echo "Error";
}
}
Save your errors in an array, then check if the array is empty at the end. If so, no errors - submit email. Else, display errors:
//dont declare separate variables,use an array
//$nameErr = $phoneErr = $emailErr = $zipErr = $serviceErr = "";
$errors = [];
if (empty($_POST["name"])) {
$errors['nameErr'] = "name required.";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$errors['nameErr'] = "letters and spaces only.";
}
}
//other validation here, then
if(empty($errors){
//no errors, submit
your_submit_function();
}else{
//display errors
foreach($errors as $val){
echo $val . '<br/>';
}
}