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"]);
}
Related
I'm recieving an issue in the following php code. I am recieiving an unknown variable error in line 146, (echo $newrecord) variable. I'm not sure what is wrong with this variable, I have defined it in the IF statement, and am simply echoing if it is successful. I originally had that segment of code (after ) at the top of the script, but it was causing issues with the mandatory field error messages displaying properly. Any help is appreciated!
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = $subErr = "";
$name = $email = $gender = $comment = $website = $sub = $newrecord = "";
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"]);
}
if (empty($_POST["Subscription"])) {
$subErr = "Subscription is required"; }
else {
$sub = test_input($_POST["Subscription"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Southern Tier Daily News</h2>
<form method="post" action="Newspaper3.php">
<input type="hidden" name="submitted" value="true"/>
<img src="https://bloximages.newyork1.vip.townnews.com/dnews.com/content/tncms/custom/image/5eec4204-483e-11e6-93c8-97ef236dc6c5.jpg?_dc=1468334339" alt="HTML5 Icon" style="width:128px;height:128px;">
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<legend>Newspaper Subscription Request</legend>
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
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
Subscription:
<select name="Subscription">
<option value=""></option>
<option value="Daily">Daily</option>
<option value="Evening">Evening</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
</select>
<span class="error">* <?php echo $subErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
<br><br>
Visit Admin Page
</fieldset>
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
echo "<br>";
echo $sub;
?>
<?php
if (isset($_POST['submitted'])) {
include('connect-mysql.php');
$fname = $_POST['Name'];
$femail = $_POST['Email'];
$fcomment = $_POST['Comment'];
$fsubsciption = $_POST['Subscription'];
$sqlinsert = "INSERT INTO newspaper (Name, Email, Comment, Subscription) VALUES ('$fname',
'$femail', '$fcomment', '$fsubsciption')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('error inserting new record');
} // end of nested if statement
$newrecord = "1 record added to the database";
} // end of main if statement
?>
<?php
echo $newrecord
?>
</body>
</html>
newrecord is defined and initialized inside the if statement, therefore if your code opts to the else, it will skip the if and your newrecord variable won't exist.
$newrecord is defined within an if statement, when the if is not executed the variable is not available. You can define it by default adding $newrecord = ''; before you start the if for the submit.
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.
I'm using a form to insert records into my database. The error checking works and the records insert correctly. The problem is the record insert message displays above the form instead of underneath it. I've tried moving the INSERT query so it dislays under the form but when I do, the error checking doesn't work. Any help resolving this would be greatly appreciated.
<p class="first"><span class="error">* required field.</span></p>
<br>
<?php
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$servername = "localhost";
$username = "oldga740_Tonymm";
$password = "JtAjDm#6";
$dbname = "oldga740_SeniorProject";
// create connection
$connection = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST['submit']) && !$connection->connect_error){
// to track errors
$error = false;
// now validate input fields
if (empty($_POST['Project']) || !isset($_POST['Project'])){
$ProjectErr = "Project name is required";
$error = true;
}elseif(!preg_match("/^[A-Za-z0-9.-]+$/",$_POST['Project'])){
// check if project only contains number, letters, comma's periods and whitespace
$ProjectErr = "Only letters, numbers, comma's, periods and white space allowed";
$error = true;
}else{
$Project = test_input($_POST['Project']);
}
if (empty($_POST['Client']) || !isset($_POST['Client'])){
$ClientErr = "Client name is required";
$error = true;
}elseif(!preg_match("/^[A-Za-z 0-9.-]+$/",$_POST['Client'])){
// check if project only contains number, letters, comma's periods and whitespace
$ClientErr = "Only letters, numbers, comma's, periods and white space allowed";
$error = true;
}else{
$Client = test_input($_POST['Client']);
}
if (empty($_POST['LastName']) || !isset($_POST['LastName'])){
$LastNameErr = "Last name is required";
$error = true;
}elseif(!preg_match("/^[A-Za-z0-9-]+$/",$_POST['LastName'])){
// check if last name only contains letters and whitespace
$LastNameErr = "Only letters and white space allowed";
$error = true;
}else{
$LastName = test_input($_POST['LastName']);
}
if (empty($_POST['DateReceived']) || !isset($_POST['DateReceived'])){
$DateReceivedErr = "Date received is required";
$error = true;
}elseif(!preg_match("/^\d{4}-\d{2}-\d{2}$/",$_POST['DateReceived'])){
// check if data received only contains letters and whitespace
$DateReceivedErr = "Date must be entered as YYYY/MM/DD";
$error = true;
}else{
$DateReceived = test_input($_POST['DateReceived']);
}
if(!$error){
$query = "INSERT INTO Projects (Project, Client, LastName, DateReceived) VALUES ('$Project', '$Client', '$LastName', '$DateReceived')";
if($connection->query($query)){
echo "record is successfully inserted!";
}else{
echo "error: record could not be inserted";
}
}
}
?>
<?php
$connection->close();
?>
<form action="http://www.oldgamer60.com/Project/NewProject.php" method="post">
<div class="fieldset">
<fieldset>
Project: <input type="text" name="Project" value="<?php if(isset($Project)){ echo $Project; } ?>">
<span class="error">* <?php if(isset($ProjectErr)){ echo $ProjectErr; } ?></span>
<br><br>
Client: <input type="text" name="Client" value="<?php if(isset($Client)){ echo $Client; } ?>">
<span class="error">* <?php if(isset($ClientErr)){ echo $ClientErr; } ?></span>
<br><br>
LastName: <input type="text" name="LastName" value="<?php if(isset($LastName)){ echo $LastName; } ?>">
<span class="error">* <?php if(isset($LastNameErr)){ echo $LastNameErr; } ?></span>
<br><br>
DateReceived: <input type="text" name="DateReceived" value="<?php if(isset($DateReceived)){ echo $DateReceived; } ?>">
<span class="error">* <?php if(isset($DateReceivedErr)){ echo $DateReceivedErr; } ?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</fieldset>
</div>
</form>
</div>
</div>
</body>
</html>
Use a variable a store the message and then display it wherever you need, like this:
// your code
if(isset($_POST['submit']) && !$connection->connect_error){
// your code
if(!$error){
$query = "INSERT INTO Projects (Project, Client, LastName, DateReceived) VALUES ('$Project', '$Client', '$LastName', '$DateReceived')";
if($connection->query($query)){
$message = "record is successfully inserted!";
}else{
$message = "error: record could not be inserted";
}
}
}
?>
<?php
$connection->close();
?>
<form action="http://www.oldgamer60.com/Project/NewProject.php" method="post">
<div class="fieldset">
<fieldset>
Project: <input type="text" name="Project" value="<?php if(isset($Project)){ echo $Project; } ?>">
<span class="error">* <?php if(isset($ProjectErr)){ echo $ProjectErr; } ?></span>
<br><br>
Client: <input type="text" name="Client" value="<?php if(isset($Client)){ echo $Client; } ?>">
<span class="error">* <?php if(isset($ClientErr)){ echo $ClientErr; } ?></span>
<br><br>
LastName: <input type="text" name="LastName" value="<?php if(isset($LastName)){ echo $LastName; } ?>">
<span class="error">* <?php if(isset($LastNameErr)){ echo $LastNameErr; } ?></span>
<br><br>
DateReceived: <input type="text" name="DateReceived" value="<?php if(isset($DateReceived)){ echo $DateReceived; } ?>">
<span class="error">* <?php if(isset($DateReceivedErr)){ echo $DateReceivedErr; } ?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</fieldset>
</div>
</form>
<?php
if(isset($message)){ echo $message; }
?>
// your code
I'm trying to do form validation and storing the validated data in mysql database using php.The code works fine as its supposed to do save the form data in mysql db after the validation process.The problem is it shows the undefined index error in these lines
1.<span class="error">* <?php echo $error['name'];?></span>
2.<span class="error">* <?php echo $error['email']; ?></span>
3.<span class="error"><?php echo $error['website']; ?></span>
4.<span class="error">* <?php echo $error['gender'];?></span>.
here is my full code.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$error=array();
$name = $email = $gender = $comment = $website = $data = "";
function test_input($data)
{
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$error['name']= "Name is required";}
else
{
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$error['name'] = "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["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))
{
$error['website'] = "Invalid URL";
}
}
if (empty($_POST["comment"]))
{$comment = "";}
else
{$comment = test_input($_POST["comment"]);}
if (empty($_POST["gender"]))
{$error['gender'] = "Gender is required";}
else
{$gender = test_input($_POST["gender"]);}
}
?>
<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 $error['name'];?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $error['email']; ?></span>
<br><br>
Website: <input type="text" name="website" value="<?php echo $website;?>">
<span class="error"><?php echo $error['website']; ?></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
<span class="error">* <?php echo $error['gender'];?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
$con=mysqli_connect("localhost","root","root","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO np_appoint (Name,Email,Website,Comment,Gender)
VALUES
('$_POST[Name]','$_POST[Email]','$_POST[website]','$_POST[Comments]','$_POST[Gender]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
</body>
</html>
To avoid undefined values use isset().
<span class="error"> <?php if(isset($error['name']))
echo $error['name'];?></span>
Its because if there is no error the $error array is not defined.
try defining the wariables at the beginning of your code>
$error['name'] = '';
$error['email'] = '';
$error['website'] = '';
$error['gender'] = '';
Your error messages are set one at a time, but the keys in $error array are not predefined. So if name is valid you will not have $error['name']. This will produce a undefined index NOTICE.
USe isset() function
<span class="error">* <?php if(isset($error['name']))
echo $error['name'];?></span>
Or error supressing using # (not recommended )
<span class="error">* <?php echo #$error['name'];?></span>
Attempting to access an array key which has not been defined is the same as accessing any other undefined variable gives an E_NOTICE-level error message like undefined index
Try this, count($error)>0
<?php if(count($error)>0){?>
<span class="error">* <?php echo $error['name'];?></span>
<?php } ?>
OR
You can use foreach
<?php foreach($error as $value){?>
<span class="error">* <?php echo $value;?></span>
<?php } ?>
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