I have a form with 3 fields, and I want to validate the fields.
Let's say that the user make a mistake or didn't introduce the email, then all other fields (name and Address) reset to blank.
Is there any way to show the error Message (Email is required) without resetting the name and address so the user doesn't have to introduce all values again?
This is a great help for user the form has multiple values.
Thank you so much
Please see my PHP code below:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $addressErr = "";
$name = $email = $address = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["address"])) {
$AddressErr = "Address is required";
} else {
$address = test_input($_POST["address"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$address)) {
$addressErr = "Only letters and white space allowed";
}
}
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is 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";
}
}
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="text" name="name" placeholder="First Name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
<input type="text" name="email" placeholder="Email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
<input type="text" name="address" placeholder="Address">
<span class="error">* <?php echo $AddressErr;?></span>
<br><br>
<input type="submit" name="submit" value="SAVE">
</form>
<?php
if ($nameErr == '' && $emailErr == '' && $AddressErr == '')
{
$db = pg_connect('host=localhost dbname=test user=samuelraul password=naikaerikamber');
$firstname = pg_escape_string($_POST['name']);
$emailaddress = pg_escape_string($_POST['email']);
$address = pg_escape_string($_POST['address']);
$query = "INSERT INTO host(firstname, emailaddress, address) VALUES('" . $firstname . "', ' '" . $emailaddress . "', '" . $address . "')";
$result = pg_query($db, $query);
if (!$result) {
$errormessage = pg_last_error();
echo "Error with query: " . $errormessage;
exit();
}
pg_close();
}
?>
</body>
</html>
You can use value="<?php echo $name;?>" for name field because you already define $name variable.You can use $email and $address variable for email and address field respectively
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="text" name="name" placeholder="First Name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
<input type="text" name="email" placeholder="Email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
<input type="text" name="address" placeholder="Address" value="<?php echo $address;?>">
<span class="error">* <?php echo $AddressErr;?></span>
<br><br>
<input type="submit" name="submit" value="SAVE">
</form>
The easiest way via PHP would look like:
<input type="text" name="name" placeholder="First Name" value="<?php echo ( isset( $_POST['name'] ) ? htmlspecialchars($_POST['name']) : '' ); ?>">
This code checks if POST[name] has been send to the server and if so, it simply sets the content as value for the input.
For the other inputs you have to replace $_POST[name] with e.g. $_POST[email].
Also I would set the input type to email, for the e-mail-address.
Related
I am creating a php form for data validation but there are some errors that I can't find.
When I submit the form the required notification is displayed. But when I reload the page then the required notification still remains. My code is:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is 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["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-
9+&##\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?>
value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?>
value="male">Male
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?>
value="other">Other
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
This is the result when I first type the address in the browser.
This is the result when I enter an empty value in all the fields and submit the form. This will remain when I reload the page and until I close the browser tab and open a new tab and enter the url again.
You got error message when you reload after form submission. Try following code into your JS file or in JS code.
<script>
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
</script>
Hope this will help you!
I am trying to set up a form for my website that is all on 1 php page (contact.php). I have went through the tutorial on w3schools and have gotten the form validation working perfectly. However, it does not send the form information anywhere. I have researched other form articles and tutorials, and although I can get some forms to email, they dont validate, and vice versa. I have tried combining this info, but it does not work.
Can someone please help me to get this code to send the form data to an email address?
Thank you.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $orgErr = $emailErr = $websiteErr = "";
$name = $org = $email = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["org"])) {
$orgErr = "Organization is required";
} else {
$org = test_input($_POST["org"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$org)) {
$orgErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name*: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error"><?php echo $nameErr;?></span>
<br><br>
Organization*: <input type="text" name="org" value="<?php echo $org;?>">
<span class="error"><?php echo $orgErr;?></span>
<br><br>
E-mail*: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error"><?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Try after your checks to use the following function:
mail();
Reference:
http://www.php.net//manual/en/function.mail.php
http://www.w3schools.com/php/php_mail.asp
I'm working on an HTML form, which is connected to MySQL database. Database is updating with new data every time, when I reload the page and also when a failed submit occur.
This is my code, Anyone please help me to add session to this page and please give me a solution
<body>
<?php
// define variables and set to empty values
$email_id = $first_name = $last_name = $district = $city = $address = $mobile_no = $password = "";
$email_idErr = $first_nameErr = $last_nameErr = $districtErr = $cityErr = $addressErr = $mobile_noErr = $passwordErr = "";
?>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
//First name validation
if(empty($_POST["first_name"]))
{$first_nameErr="First name is required";}
else
{$first_name = test_input($_POST["first_name"]);
//checking name formats
if(!preg_match("/^[a-zA-Z]*$/",$first_name))
{$first_nameErr="Only letters and white spaces allowed";}
}
//Second name validation
if(empty($_POST["last_name"]))
{$last_nameErr="Last name is required";}
else
{$last_name = test_input($_POST["last_name"]);
//checking name formats
if(!preg_match("/^[a-zA-Z]*$/",$last_name))
{$last_nameErr="Only letters and white spaces allowed";}
}
//E-mail validation
if(empty($_POST["email_id"]))
{$email_idErr="E-mail id is required";}
else
{$email_id = test_input($_POST["email_id"]);
//checking email format
if(!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email_id))
{$email_idErr="Invalid email format";}
}
//District is required
if(empty($_POST["district"]))
{ $districtErr="District is required";}
else
{ $district = test_input($_POST["district"]);
if(!preg_match("/^[a-zA-Z]*$/",$district))
{$districtErr="Only letters and white spaces allowed";}
}
$city = test_input($_POST["city"]);
$address = test_input($_POST["address"]);
//Mobile number validation
if(empty($_POST["mobile_no"]))
{$mobile_noErr="Mobile number is required";}
else
{$mobile_no = test_input($_POST["mobile_no"]);
if(!preg_match("/^[0-9]*$/",$mobile_no))
{$mobile_noErr="Invalid Mobile number";}
}
//Password validation
if(empty($_POST["password"]))
{$passwordErr="Password is required";}
else
{ $password = test_input($_POST["password"]);
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<?php
$con=mysqli_connect("localhost","root","","ashlyn");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{echo "Connection Established";}
$sql="INSERT INTO user_details (email_id, first_name, last_name, district, city, address, mobile_no, password)
VALUES ('$email_id', '$first_name', '$last_name', '$district', '$city', '$address', '$mobile_no', '$password')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "You are successfully registered..";
mysqli_close($con);
?>
<section class="container">
<div class="login">
<h1>User Login Page</h1>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);>">
<p><input type="text" name="first_name" value="" placeholder="First Name"><span class="error">* <?php echo $first_nameErr;?></span></p>
<p><input type="text" name="last_name" value="" placeholder="Last Name"> <span class="error">* <?php echo $last_nameErr;?></span>
</p>
<p><input type="text" name="email_id" value="" placeholder="Email"><span class="error">* <?php echo $email_idErr;?></span>
</p>
<p><input type="text" name="district" value="" placeholder="District"><span class="error">* <?php echo $districtErr;?></span></p>
<p><input type="text" name="city" value="" placeholder="City">
</p>
<p><input type="text" name="address" value="" placeholder="Address">
</p>
<p><input type="text" name="mobile_no" value="" placeholder="Mobile Number"> <span class="error">* <?php echo $mobile_noErr;?></span>
</p>
<p><input type="password" name="password" value="" placeholder="Password"> <span class="error">* <?php echo $passwordErr;?></span>
</p>
<p class="submit"><input type="submit" name="submit" value="Submit"></p>
</form>
what you need is
<?php session_start();
on the first line bevor any output
https://stackoverflow.com/a/8084900/1792420
I'm doing the form validation using php.I'm trying to access the php file from my form(<form action="appoint.php">).But it shows me undefined variable error at each of the form elements.(code works well when i use the
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">which means i used form(html) and php in the same file.
here is my form code:
<form method="post" action="appoint.php">First Name:
<input type="text" name="fname" value="<?php echo $fname;?>"> <span class="error">* <?php if(isset($error['fname']))
echo $error['fname'];?></span>
<br>
<br>Last Name:
<input type="text" name="lname" value="<?php echo $lname;?>"> <span class="error">* <?php if(isset($error['lname']))
echo $error['lname'];?></span>
<br>
<br>E-mail:
<input type="text" name="email" value="<?php echo $email;?>"> <span class="error">* <?php if(isset($error['email']))
echo $error['email'];?></span>
<br>
<br>Phone-no:
<input type="text" name="phone_no" value="<?php echo $phone_no;?>"> <span class="error">* <?php if(isset($error['phone_no']))
echo $error['phone_no'];?></span>
<br>
<br>Date:
<input type="text" name="date" value="<?php echo $date;?>"> <span class="error">* <?php if(isset($error['date']))
echo $error['date'];?></span>
<br>
<br>Time:
<input type="text" name="time" value="<?php echo $time;?>"> <span class="error">* <?php if(isset($error['time']))
echo $error['time'];?></span>
<br>
<br>Physician:
<input type="text" name="physician" value="<?php echo $physician;?>"> <span class="error">* <?php if(isset($error['physician']))
echo $error['physician'];?></span>
<br>
<br>Remarks :
<input type="text" name="remarks" value="<?php echo $remarks;?>"> <span class="error">* <?php if(isset($error['remarks']))
echo $error['remarks'];?></span>
complaint:
<textarea name="complaint" rows="5" cols="40" value="<?php echo $complaint;?>"></textarea> <span class="error">* <?php if(isset($error['complaint']))
echo $error['complaint'];?></span>
<br>
<br>
<input type="submit" name="submit" value="Submit">
</form>
and here is my appoint.php
`
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["fname"]))
{$error['fname']= "First Name is required";}
else
{
$fname = test_input($_POST["fname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$fname))
{
$error['fname'] = "Only letters and white space allowed";
}
}
if (empty($_POST["lname"]))
{$error['lname']= "Last Name is required";}
else
{
$lname = test_input($_POST["lname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lname))
{
$error['lname'] = "Only letters and white space allowed";
}
}
if (empty($_POST["email"]))
{$error['email'] = "Email is required";}
else
{
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$error['email'] = "Invalid email format";
}
}
if (empty($_POST["phone_no"]))
{$phone_no = '00-0000-0000';}
else
{
$phone_no = test_input($_POST["phone_no"]);
// check if phone.no is valid//
if(!preg_match("/^[0-9]{2}-[0-9]{4}-[0-9]{4}$/", $phone_no))
{
$error['phone_no'] = "Invalid Number";
}
}
if (empty($_POST["date"]))
{$error['date'] = "Date is required";}
else
{$date= test_input($_POST["date"]);}
if (empty($_POST["time"]))
{$error['time'] = "Time is required";}
else
{$time = test_input($_POST["time"]);}
if(empty($_POST["physician"]))
{$error['physician']="select a physician";}
else {$physician=test_input($_POST["physician"]);
}
if (empty($_POST["remarks"]))
{$error['remarks'] ="";}
else
{
$remarks = test_input($_POST["remarks"]);}
if (empty($_POST["complaint"]))
{$error['complaint'] = " complaint is required";}
else
{
$complaint = test_input($_POST["complaint"]);}
if(empty($error))
{$con=mysqli_connect("localhost","root","root","my_db1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO np_appointment(fname,lname,date,time,email,phone_no,
physician,remarks,complaint)
VALUES
('$_POST[fname]','$_POST[lname]','$_POST[date]',
'$_POST[time]','$_POST[email]','$_POST[phone_no]',
'$_POST[physician]','$_POST[remarks]','$_POST[complaint]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con); }
}
?>
`
You can try a different approach:
Make all the fields required in html.
<input type="text" name="fname" value="<?php echo $fname;?>" required>
Then on the php do this. Define the variable outside the if-else sections.:
$fname = '';
if (empty($_POST["fname"]))
{$error['fname']= "First Name is required";}
else
{
$fname = test_input($_POST["fname"]);
}
My php self-validating form is submitting to sql database whether the characters entered into form fields are appropriate or not...How do stop it from submitting until the conditions for each form field are met?
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>RSG Contact Us</title>
<script>
// $(function () {
// $('form').on('submit', function (e) {
// $.ajax({
// type: 'post',
// url: 'contact.php',
// data: $('form').serialize(),
// success: function () {
// alert('Thank you! your form has been submitted');
// }
// });
// e.preventDefault();
// });
// });
</script>
</head>
<body>
<div id="contactuscall">
<?php
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// define variables and set to empty values
$firstnameErr = $lastnameErr = $emailErr = $cellphoneErr = $genDerErr = $dognameErr = $BreedErr = $reasonErr = "";
$firstname = $lastname = $email = $cellphone = $genDer = $dogname = $Breed = $reasoN= $freecomments = "";
//if conditional statement stops PHP from looking for variable values until the submit button is hit
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// check if a first name was provided
if (empty($_POST["firstname"]))
{$firstnameErr = "A first name is required";}
else
{
$firstname = test_input($_POST["firstname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstname))
{$firstnameErr = "Only letters and white space allowed";}
}
//check if a last name was provided
if (empty($_POST["lastname"]))
{$lastnameErr = "A last name is required";}
else
{
$lastname = test_input($_POST["lastname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lastname))
{
$lastnameErr = "Only letters and white space allowed";
}
}
// check if an email was provided
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}
}
if (empty($_POST["cellphone"]))
{$cellphoneErr = "Please provide a phone number";}
else {
$cellphone = test_input($_POST["cellphone"]);
// Regular Expression to allow only valid phone number formats, including numbers, spaces, dashes, extensions
if (!preg_match("/^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/",$cellphone))
{$cellphoneErr = "Invalid format";}
}
if (empty($_POST["dogname"]))
{$dognameErr = "A doggy name is required";}
else {
$dogname = test_input($_POST["dogname"]);
// check if dogname only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$dogname))
{$dognameErr = "Only letters and white space allowed";}
}
if (empty($_POST["Breed"]))
{$BreedErr = "A breed name is required";}
else {
$Breed = test_input($_POST["Breed"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$Breed))
{$BreedErr = "Only letters and white space allowed";}
}
if(empty($_POST['genDer']))
{$genDerErr= "You forgot to select a Gender!";}
else {
$genDer=($_POST['genDer']);
}
//make sure one of the services requested checkboxes are checked
$reasoN = $_POST['reasoN'];
if(empty($reasoN))
{
$reasonErr="You didn't select any services.";
}
else
{
$N = count($reasoN);
$reasonErr="You selected $N services(s): ";
}
// if comment section is not empty then run test_input function to purge possible malicious code
if (empty($_POST["freecomments"]))
{$freecomments = "";}
else
{$freecomments = test_input($_POST["freecomments"]);}
}
$host="fdb3.biz.nf"; //localhost
$dbuser="1546259_rsginfo"; //user
$dbpass="RSGnow12"; //pass
$dbname="1546259_rsginfo"; //db name
// Create connection
$conn=mysqli_connect($host,$dbuser,$dbpass,$dbname);
// Check connection
if (mysqli_connect_errno($conn))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//create query
$sql= "INSERT INTO customer (fname, lname, email, phone, comments)VALUES ('$firstname', '$lastname', '$email', '$cellphone', '$freecomments')";
$sql2= "INSERT INTO DogInfo (DogName, Breed, Lookingfor)VALUES ('$dogname', '$Breed', '$reasoN')";
// execute query
mysqli_query($conn,$sql);
mysqli_query($conn, $sql2);
// close connection
mysqli_close($conn)
?>
<form id="form1" name="form1" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
<fieldset id="field1">
<legend id="legend1">Contact info:</legend>
<hr />
First name: <input type="text" id="firstname" name="firstname" size="30" class="textfield" value="<?php echo $firstname;?>">
<span class="error">* <?php echo $firstnameErr;?></span>
E-mail: <input type="text" size="30" name="email" class="textfield" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span><br />
Last name: <input type="text" id="lastname" name="lastname" size="30" class="textfield" value="<?php echo $lastname;?>">
<span class="error">* <?php echo $lastnameErr;?></span>
Cell: <input type="text" id="cellphone" name="cellphone" size="30" class="textfield" value="<?php echo $cellphone;?>">
<span class="error">* <?php echo $cellphoneErr;?></span><br />
</fieldset>
<fieldset id="field2">
<legend id="legend2">Doggie info:</legend>
<hr />
Name: <input type="text" id="dogname" name="dogname" size="20" class="textfield" value="<?php echo $dogname;?>"><span class="error">* <?php echo $dognameErr;?></span>
Breed: <input type="text" id="Breed" name="Breed" size="20" class="textfield" value="<?php echo $Breed;?>"><span class="error">* <?php echo $BreedErr;?></span>
<p>
Gender:<select name="genDer" class="textfield">
<option value="">--</option>
<option value="Intact Male" <?php echo isset($_POST['genDer']) && $_POST['genDer'] == "Intact Male" ? "selected" : "" ?>>Intact Male</option>
<option value="Neutered Male"<?php echo isset($_POST['genDer']) && $_POST['genDer'] == "Neutered Male" ? "selected" : "" ?>>Neutered Male</option>
<option value="Intact Female"<?php echo isset($_POST['genDer']) && $_POST['genDer'] == "Intact Female" ? "selected" : "" ?>>Intact Female</option>
<option value="Neutered Female"<?php echo isset($_POST['genDer']) && $_POST['genDer'] == "Neutered Female" ? "selected" : "" ?>>Neutered Female</option>
</select><span class="error">* <?php echo $genDerErr;?></span>
</p>
</fieldset>
<fieldset id="field3">
<legend id="legend3">Services Required:</legend>
<hr />
<input type="checkbox" name="reasoN[]" value="walkSale"
<?php if(isset($_POST['reasoN'])) echo "checked='checked'";?> class="textfield"/>I'm looking for a Dog Walker!
<input type="checkbox" name="reasoN[]" value="RawSale"
<?php if(isset($_POST['reasoN'])) echo "checked='checked'";?> class="textfield"/>I'm looking to purchase Raw Food!
<input type="checkbox" name="reasoN[]" value="groomSale"
<?php if(isset($_POST['reasoN'])) echo "checked='checked'";?> class="textfield"/>I'm looking for a Dog Groomer!
<span class="error">* <?php echo $reasonErr;?></span>
<?php echo $reasonConfirm;?>
</fieldset>
<fieldset id="field4">
<legend id="legend4">Comments & Questions</legend>
<hr />
<textarea rows="7" cols="90" id="freecomments" name="freecomments"><?php echo $freecomments;?></textarea>
</fieldset>
<input id="submit" type="submit" name="submit" value="submit">
</form>
</div>
<?php
echo "<h2>Your Input:</h2>";
echo $firstname;
echo "<br>";
echo $lastname;
echo "<br>";
echo $email;
echo "<br>";
echo $cellphone;
echo "<br>";
echo $dogname;
echo "<br>";
echo $Breed;
echo "<br>";
echo $genDer;
echo "<br>";
echo $reasoN;
echo "<br>";
echo $freecomments;
?>
</body>
</html>
Your code actually tries to insert values in to the table whether or not the validation is successful. The easiest and the quickest solution for this is to use a boolean flag.
eg:
// ...
$formValid = true; // Define a boolean and set to true before validating
//if conditional statement stops PHP from looking for variable values until the submit button is hit
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// check if a first name was provided
if (empty($_POST["firstname"]))
{
$firstnameErr = "A first name is required";
} else {
$firstname = test_input($_POST["firstname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstname))
{
$firstnameErr = "Only letters and white space allowed";
$formValid = false; // Invalid input - set the flag to false
}
}
}
// ....
// Eventually wrap the mysql logic inside a condition
if ($formValid)
{
// Create connection
$conn=mysqli_connect($host,$dbuser,$dbpass,$dbname);
// Check connection
if (mysqli_connect_errno($conn))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//create query
$sql= "INSERT INTO customer (fname, lname, email, phone, comments)VALUES ('$firstname', '$lastname', '$email', '$cellphone', '$freecomments')";
$sql2= "INSERT INTO DogInfo (DogName, Breed, Lookingfor)VALUES ('$dogname', '$Breed', '$reasoN')";
// execute query
mysqli_query($conn,$sql);
mysqli_query($conn, $sql2);
// close connection
mysqli_close($conn);
}
// ... rest of your code