I am fairly new at PHP. I have an assignment which requires me to make two separate files. On called input.html and the other handle.php.
The input.html file has a for that will receive user input and then send it to the handle.php file.
The input.html should look like
and if all the fields are filed in then I should display this
The complication that I'm having is with the required filed. If the fields do not have text or the radio is not checked then it should warn users but with me it keep sending them to the PHP file and showing an error.
My code for input.html is
<!doctype html>
<html lang="en">
<head>
<title> Feedback Form </title>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $responseErr = $commentErr = "";
$name = $email = $response = $comment = "";
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 email address is well-formated
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email format";
}
}
if (empty($_POST["response"])) {
$responseErr = "Response is required";
} else {
$response = test_input($_POST["response"]);
}
if (empty($_POST["comment"])) {
$commentErr = "Comment is required";
} else {
$comment = test_input($_POST["comment"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<p>Please complete this form to submit your feedback:</p>
<p><span class="error">* required field</span></p>
<!-- Start of the form -->
<form method="post" action="handle.php">
Name: <select name="prefix">
<option>Mr. </option>
<option>Mrs. </option>
<option>Ms. </option>
</select> <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Email Address: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Response: This is...
<input type="radio" name="response" value="excellent">excellent
<input type="radio" name="response" value="okay">okay
<input type="radio" name="response" value="boring">boring
<span class="error">* <?php echo $responseErr;?></span>
<br><br>
Comments: <textarea name="comment" rows="5" cols="40"></textarea>
<span class="error">* <?php echo $commentErr;?></span>
<br><br>
<input type="submit" value="Send My Feedback">
</form>
<!-- End of the form -->
</body>
</html>
and my code for handle.php is
<html>
<head></head>
<body>
Thank you, <?php echo $_POST["prefix"] ?> <?php echo $_POST["name"]; ?> for your comment.<br><br>
You stated that you found this example to be '<?php echo $_POST["response"]; ?>'<br>
and added: <br>
'<?php echo $_POST['comment'];?>'<br>
</body>
</html>
So when I leave all the fields blank instead of it warning me that they are blank i get this
I tried to use w3shool as a guide line but it did not work. I would really appreciate some help and thank you to everything that is taking their time to attempt to help me. :)
You can use required to solve your problem. required stops the form from submitting if the required field is empty or not selected.
<form method="post" action="handle.php">
Name:
<select name="prefix">
<option>Mr. </option>
<option>Mrs. </option>
<option>Ms. </option>
</select>
<input type="text" name="name" required>
<span class="error">* <?php echo $nameErr;?></span>
<br>
<br> Email Address:
<input type="email" name="email" required>
<span class="error">* <?php echo $emailErr;?></span>
<br>
<br> Response: This is...
<input type="radio" name="response" value="excellent" required>excellent
<input type="radio" name="response" value="okay" required>okay
<input type="radio" name="response" value="boring" required>boring
<span class="error">* <?php echo $responseErr;?></span>
<br>
<br> Comments:
<textarea name="comment" rows="5" cols="40" required></textarea>
<span class="error">* <?php echo $commentErr;?></span>
<br>
<br>
<input type="submit" value="Send My Feedback">
</form>
I also recommend to use 'email' as type for email input field. This will make sure the input data is a valid email format.
I am trying to Show an error message besides the input fields but I am not able to do so. I am not able to find what mistake I am making here. Below is the code of form and PHP. My code looks to me right but in browser I am not getting desired output as I am stuck on it. I would be thankful if some would help me.
<?php
$Name_Error = "";
$Email_Error="";
$Website_Error="";
$Gender_Error="";
function Test_User_Input($User_Data){
return $User_Data;
}
if(isset($_POST['Submit'])){
if(empty($_POST["Name"])){
$Name_Error = "Kindly Enter the Name!";
}
else {
$Name = Test_User_Input($_POST["Name"]);
}
if(empty($_POST["Email"])){
$Email_Error = "Kindly Enter the Eamil Address!";
}
else {
$Email = Test_User_Input($_POST["Email"]);
}
if(empty($_POST["Website"])){
$Website_Error = "Kindly Enter the Website URL!";
}
else {
$Website = Test_User_Input($_POST["Website"]);
}
if(empty($_POST["Gender"])) {
$Gender_Error = "Kindly Select your Gender!";
}
else {
$Gender = Test_User_Input($_POST["Gender"]);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Simple Form</title>
</head>
<body>
<form>
<label>Enter your Name</label>
<br>
<input type="text" name="Name">*<?php echo $Name_Error ?>
<br>
<label>Enter your Email Address</label>
<br>
<input type="text" name="Email">*<?php echo $Email_Error ?>
<br>
<label>Enter your Website</label>
<br>
<input type="text" name="Website">*<?php echo $Website_Error ?>
<br>
<label>Select your Gender</label>
<br>
<input type="radio" name="Gender" value="Male"> Male
<input type="radio" name="Gender" value="Female">Female *<?php echo $Gender_Error ?>
<br>
<label>Comments
<br>
<textarea name="Comment"></textarea>
<br>
<input type="Submit" name="Submit">
</form>
</body>
</html>
You need to call a specific page to trigger your PHP, in this case it's the page itself, the method is POST
change <form> to <form action="" method="POST">
Add form action="" and method="POST". That will fix your problem.
<?php
$Name_Error = $Email_Error = $Gender_Error = $Website_Error = "";
$Name = $Email = $Gender = $Website = "";
if(isset($_POST['Submit'])){
if (empty($_POST["Name"])) {
$Name_Error = "Name is required";
} else {
$Name = test_input($_POST["Name"]);
}
if (empty($_POST["Email"])) {
$Email_Error = "Email is required";
} else {
$Email = test_input($_POST["Email"]);
}
if (empty($_POST["Website"])) {
$Website_Error = "Kindly Enter the Website URL!";
} else {
$Website = test_input($_POST["Website"]);
}
if (empty($_POST["Gender"])) {
$Gender_Error = "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">
<span class="error">* <?php echo $Name_Error;?></span>
<br><br>
E-mail: <input type="text" name="Email">
<span class="error">* <?php echo $Email_Error;?></span>
<br><br>
Website: <input type="text" name="Website">
<span class="error"><?php echo $Website_Error;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="Gender" value="female">Female
<input type="radio" name="Gender" value="male">Male
<input type="radio" name="Gender" value="other">Other
<span class="error">* <?php echo $Gender_Error;?></span>
<br><br>
<input type="submit" name="Submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $Name;
echo "<br>";
echo $Email;
echo "<br>";
echo $Website;
echo "<br>";
echo $Gender;
?>
</body>
</html>
This wont display the error message in submission, I don't know what is wrong, my code seems alright to me. For some reason, the error code within the span elements fails the display the error message when the text failed. Not even the data echoed out was printed after the submission of the form.
<body>
<form method="post" action="<?php echo
$_SERVER['PHP_SELF']; ?>">
<label>
<input type="text" placeholder="Enter
fullname here" name="name">
<span class="err"><?php echo #$name_err; ?></span>
</label>
<label>
<input type="text" placeholder="Enter
Email here" name="email">
<span class="err"><?php echo #$email_err; ?></span>
</label>
<label>
<input type="submit" value="submit">
</label>
</form>
</body>
</html>
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $email = '';
$name_err = $email_err = '';
if(!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
$name_err = 'You fullname is required';
}
if(!empty($_POST['email'])) {
$email = $_POST['email'];
}else {
$email_err = 'Your email is required';
}
}
echo $name.'<br>';
echo $email.'<br>';
?>
This should work. You should check your errors before rendering form. Also you had wrong variable name for $email_err
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $email = '';
$name_err = $email_err = '';
if(!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
$name_err = 'You fullname is required';
}
if(!empty($_POST['email'])) {
$email = $_POST['email'];
}else {
$email_err = 'Your email is required';
}
}
echo $name.'<br>';
echo $email.'<br>';
?>
<body>
<form method="post" action="<?php echo
$_SERVER['PHP_SELF']; ?>">
<label>
<input type="text" placeholder="Enter
fullname here" name="name">
<span class="err"><?php echo #$name_err; ?></span>
</label>
<label>
<input type="text" placeholder="Enter
Email here" name="email">
<span class="err"><?php echo #$email_err; ?></span>
</label>
<label>
<input type="submit" value="submit">
</label>
</form>
</body>
</html>
I'm having a big problem with my validation form. Basically I created a form that will, once submitted, redirect to another page. To do this I used header("location: aaaaa.php") and apparently it works. The problem is that by doing this the validation doesn't work anymore, in fact if I don't enter any data and press submit I'll be redirected to the second page without getting the errors. If I delete the header the validation works again.
Moreover I have a big problem with the session method. I tried different way of using it to transfer the data to the second page when pressed the button submit, but it doesn't work and no one until now was able to help me. In the code that I'm gonna put below I deleted the session method and I was hoping that you would help me with that.
London Flight Agency
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name =($_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["surname"])) {
$surnameErr = "Surname is required";
} else {
$surname =($_POST["surname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$surname)) {
$surnameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email =($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["telephone"])) {
$telephoneErr = "Number is required";
} else {
$telephone =($_POST["telephone"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[0-9\_]{7,20}/",$telephone)) {
$telephoneErr = "Enter correct telephone number";
}
}
if (empty($_POST["date"])) {
$dateErr = "Date is required";
} else {
$date =($_POST["date"]);
// check if name only contains letters and whitespace
if (!preg_match("~^\\d{1,2}[/.-]\\d{2}[/.-]\\d{4}$~",$date)) {
$dateErr = "Enter correct date of birth";
}
}
if (empty($_POST["luggage"])) {
$luggageErr = "Choose one of the options";
} else {
$luggage =($_POST["luggage"]);
}
$weight = $_POST['weight'];
$height = $_POST['height'];
if(isset($_POST['submit']))
{
$total = ($weight+$height)/10;
}
header("Location: thankyou.php");
}
?>
<h2 id="title">London Flight Agency</h2><!-- This tag is used to define HTML heading (h1 to h6), this particular one defines the most important heading -->
<form id="form" method="post" name="myForm" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" onsubmit="return validateForm(this);"><!-- The <form> tag is used to create an HTML form for user input -->
<h4 class="subtitle"><strong>Personal Details</strong></h4>
<fieldset>
Enter here all your details (all of them are compulsory.)
<br />
<br />
<select name="Title" id="title" value="<?php echo $title;?>" onblur="validateSelect(name)">
<option value="empty">Title</option>
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="Miss">Miss</option>
<option value="Dr">Dr</option>
</select><br /><br />
<span class="validateError" id="titleError" style="display: none;">You must select a title!</span>
<span id="error8"><?php echo $titleErr;?></span>
<table
<tr>
<td><label for="firstname">First Name:</label></td>
<td><input type="text" name="name" value="<?php echo $name;?>" id="name" onblur="validateName(name)"></td>
<span id="nameError" style="display: none;"></span>
<span id="error1"><?php echo $nameErr;?></span>
</tr>
<tr>
<td><label for="surname">Surname:</label></td>
<td><input type="text" name="surname" value="<?php echo $surname;?>" id="name" onblur="validateSurname(surname)"></td>
<span id="surnameError" style="display: none;"></span>
<span id="error2"><?php echo $surnameErr;?></span>
</tr>
<tr>
<td><label for="email">Email address:</label></td>
<td><input type="text" name="email" value="<?php echo $email;?>" id="email" onblur="validateEmail(email)"></td>
<span id="emailError" style="display: none;"></span>
<span id="error3"><?php echo $emailErr;?></span>
</tr>
<tr>
<td><label for="telephone">Telephone No:</label></td>
<td><input type="text" name="telephone" value="<?php echo $telephone;?>" id="telephone" onblur="validateTelephone(telephone)"></td>
<span id="telephoneError" style="display: none;"></span>
<span id="error4"><?php echo $telephoneErr;?></span>
</tr>
<tr>
<td><label for="date">Date of birth:</label></td>
<td><input type="text" name="date" value="<?php echo $date;?>" id="date" onblur="validateDate(date)"></td>
<span id="dateError" style="display: none;"></span>
<span id="error5"><?php echo $dateErr;?></span>
</tr>
</table>
</fieldset>
<h4 class="subtitle"><strong>Flight Details</strong></h4>
<fieldset>
<p>Hand luggage:</p><br />
<input type="radio" name="luggage" <?php if (isset($luggage) && $luggage=="Yes") echo "checked";?>value="Yes" id = "myRadio" required onblur="myFunction()">Yes
<input type="radio" name="luggage" <?php if (isset($luggage) && $luggage=="No") echo "checked";?>value="No" id = "myRadio" required onblur="myFunction()">No
<span id="luggageError" style="display: none;"></span>
<span id="error6"><?php echo $luggageErr;?></span>
<br /><br />
<label for="extrabag">Include free extra bag</label>
<input type="checkbox" name="extra" id="check" value="bag">
<br />
<br />
<select name="option" id="card" onblur="validatePayment(card)">
<option value="empty">Payment Card</option>
<option value="Visa">Visa Debit Card</option>
<option value="MasterCard">MasterCard</option>
<option value="PayPal">PayPal</option>
<option value="Maestro">Mestro</option>
<option value="Visa Electron">Visa Electron</option>
</select><br />
<span class="validateError" id="cardError" style="display: none;">You must select your payment card!</span>
</fieldset>
<h4 class="subtitle"><strong>Luggage Details</strong></h4>
<fieldset>
<p>Enter weight and height of your luggage.</p>
Your Weight(kg): <input type="text" name="weight" size="7"><br />
Your Height(cm): <input type="text" name="height" size="7"><br />
<span id="error7"><?php echo $measureErr;?></span>
<input type="button" value="Tot. price" onClick="totalPrice()"><br /><br />
Total Price: <input type="text" name="total" value="<?php echo $total?>" size="10"><br /><br />
<input type="reset" value="Reset">
<input type="submit" value="Submit" name="submit">
</fieldset>
</form>
</body>
It doesn't show the first part of the code for I don't know which reason. I'll post it below:
London Flight Agency
The problem Is that you are checking if the method is post then redirect to the new page.
You must check if the your entries are valid then redirect.
For Example You can make an array of data and use array_push to push new data whenever there is something invalid and then check like this :
if( count( $array ) == 0 )
header('Location:YOUR_NEW_PAGE.php');
This is one of the simplest solutions you can implement.
Good luck
I am new to php here's the my code.
when any of the field is empty i want to stop form submission...
<!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 if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else if (empty($_POST["website"]))
{$website = "";}
else if (empty($_POST["comment"]))
{$comment = "";}
else if (empty($_POST["gender"]))
{$genderErr = "Gender is required";}
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="welcome.php">
<label>Name:</label> <input type="text" name="name"> <span class="error">* <?php echo $nameErr;?></span>
<br><br>
<label>E-mail:</label> <input type="text" name="email"> <span class="error">* <?php echo $emailErr;?></span>
<br><br>
<label>Website:</label> <input type="text" name="website"> <span class="error"><?php echo $websiteErr;?></span>
<br><br>
<label>Comment:</label> <input type="text" name="comment">
<br><br>
<label>Gender:</label>
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
If you want to print all the errors, so your code should be like below...
<?php session_start(); error_reporting(0);?>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$_SESSION['name']= "Name is required";}
if (empty($_POST["email"]))
{$_SESSION['email'] = "Email is required";}
if (empty($_POST["website"]))
{$_SESSION['website'] = "Website is required";}
if (empty($_POST["comment"]))
{$_SESSION['comment'] = "comment is required";}
if (empty($_POST["gender"]))
{$_SESSION['gender'] = "Gender is required";}
}
if($_POST['name']!="" && $_POST['email']!="" && $_POST['website']!="" &&
$_POST['gender']!="")
{
header("Location: welcome.php");
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="">
<label>Name:</label> <input type="text" name="name"> <span class="error">* <?php echo $_SESSION['name'];?></span>
<br><br>
<label>E-mail:</label> <input type="text" name="email"> <span class="error">* <?php echo $_SESSION['email'];?></span>
<br><br>
<label>Website:</label> <input type="text" name="website"> <span class="error"><?php echo $_SESSION['website'];?></span>
<br><br>
<label>Comment:</label> <input type="text" name="comment">
<br><br>
<label>Gender:</label>
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">* <?php echo $_SESSION['gender'];?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
<?php
unset($_SESSION['name']);
unset($_SESSION['email']);
unset($_SESSION['website']);
unset($_SESSION['comment']);
unset($_SESSION['gender']);
?>
If you want to access all the variables in Welcome page. just code like below
home.php
<?php session_start(); error_reporting(0);?>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="welcome.php">
<label>Name:</label> <input type="text" name="name"> <span class="error">* <?php echo $_SESSION['name'];?></span>
<br><br>
<label>E-mail:</label> <input type="text" name="email"> <span class="error">* <?php echo $_SESSION['email'];?></span>
<br><br>
<label>Website:</label> <input type="text" name="website"> <span class="error"><?php echo $_SESSION['website'];?></span>
<br><br>
<label>Comment:</label> <input type="text" name="comment">
<br><br>
<label>Gender:</label>
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">* <?php echo $_SESSION['gender'];?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
<?php
unset($_SESSION['name']);
unset($_SESSION['email']);
unset($_SESSION['website']);
unset($_SESSION['comment']);
unset($_SESSION['gender']);
?>
welcome.php
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$_SESSION['name']= "Name is required";}
if (empty($_POST["email"]))
{$_SESSION['email'] = "Email is required";}
if (empty($_POST["website"]))
{$_SESSION['website'] = "Website is required";}
if (empty($_POST["comment"]))
{$_SESSION['comment'] = "comment is required";}
if (empty($_POST["gender"]))
{$_SESSION['gender'] = "Gender is required";}
}
if(empty($_POST["name"]) || empty($_POST["email"]) || empty($_POST["website"]) || empty($_POST["gender"]))
{
header("Location: home.php");
}
echo $_POST['name'];
?>
If you want to validate your data before you submit,you should be using javascript more specifically jquery to validate the data client side itself,
Give the form an id like this
method="post" action="welcome.php" id="form1"
and ids to all your form elements
$('#form1').submit(function() {
your validation rules here
if($('#email').val().length == 0)
return false;
else
return true;
});
return false stops the submission.
If you are going to do front end and not just php you should really have a go at jquery will make your life easier
Javascript is client side, PHP is server side so until the submit button is not pressed to "Post data to server" and from there you use php to validate the form .. check fields do different operations like database inserts, calculations etc, you cannot send a response back to the client and tell him you here mate got this error i ain't going to work with this kind of data. Well, you could use ajax to live validate the form on server side. the best way to do is to validate client side and then before you use all that data that comes from the client who always lies because everybody lies you do another checking on server. Here is an example.
It sounds like you want to do the validation in PHP, but stop submitting data to PHP. That isn't possible. If you'd like to validate in PHP, all the data will be submitted no matter what. You can use exit() to stop PHP executing if you need to. Otherwise, you'll need to validate the form client-side using JavaScript (something you can find plenty of information about here or through Google).
I you need form doesn't get submitted if any of the field is empty why don't you try this..
<label>Name:</label> <input type="text" name="name" required> <span class="error">* <?php echo $nameErr;?></span>
<br><br>
<label>E-mail:</label> <input type="text" name="email" required> <span class="error">* <?php echo $emailErr;?></span>
<br><br>
<label>Website:</label> <input type="text" name="website" required> <span class="error"><?php echo $websiteErr;?></span>
<br><br>
<label>Comment:</label> <input type="text" name="comment" required>
<br><br>
<label>Gender:</label>
<input type="radio" name="gender" value="female" required>Female
<input type="radio" name="gender" value="male" required>Male
This is another way to do it with PHP for the PDO Database:
It won't submit to your database until you complete all the required fields and will also display the required input error messages.
It won't clear all the fields if you forget to fill in one of the required fields and submit.
I added an If statement to the connection.
<?php
// define variables and set to empty values
$nameErr = $emailErr = $cityErr = $commentErr = $genderErr = "";
$name = $email = $city = $comment = $gender = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Please add a name";
} else {
$name = validateInput($_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 = "Please add an email";
} else {
$email = validateInput($_POST["email"]);
// check if email is an email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email format";
}
}
if (empty($_POST["city"])) {
$cityErr = "Please add your city";
} else {
$city = validateInput($_POST["city"]);
// check if city only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$city)) {
$cityErr = "Only letters and white space allowed";
}
}
if (empty($_POST["comment"])) {
$commentErr = "Please add your comment";
} else {
$comment = validateInput($_POST["comment"]);
// check if comment only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comment)) {
$commentErr = 'Only "/", "-", "+", and numbers';
}
}
if (empty($_POST["gender"])) {
$genderErr = "Please pick your gender";
} else {
$gender = validateInput($_POST["gender"]);
}
}
// Validate Form Data
function validateInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["city"]) && !empty($_POST["comment"]) && !empty($_POST["gender"]))
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO info (name, email, city, comment, gender)
VALUES ('$name', '$email', '$city', '$comment', '$gender')";
// use exec() because no results are returned
$conn->exec($sql);
echo "Success! Form Submitted!";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>PHP Form</h2>
<p>Doesn't submit until the required fields you want are filled</p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="error">
<p><span>* required field</span></p>
<div><?php echo $nameErr;?></div>
<div><?php echo $emailErr;?></div>
<div><?php echo $cityErr;?></div>
<div><?php echo $commentErr;?></div>
<div><?php echo $genderErr;?></div>
</div>
<label for="name">Name:
<input type="text" name="name" id="name" placeholder="" value="<?php echo $name;?>">
<span class="error">*</span>
</label>
<label for="email">Email:
<input type="email" name="email" id="email" placeholder="" value="<?php echo $email;?>">
<span class="error">*</span>
</label>
<label for="city">city:
<input type="text" name="city" id="city" placeholder="" value="<?php echo $city;?>">
<span class="error">*</span>
</label>
<label for="comment">comment:
<input type="text" name="comment" id="comment" value="<?php echo $comment;?>">
<span class="error">*</span>
</label>
<label for="gender">Gender:<br>
<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">*</span>
</label>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Use this if you want to redirect it to another page so it won't send the form again to your PDO database if they refresh it.
It won't submit to your database and will stay on the HOME.PHP page until you complete all the required fields and will also display the required input error messages while on HOME.PHP page.
It won't clear all the fields if you forget to fill in one of the required fields and submit.
Added a "header("Location: welcome.php");" after "$conn->exec($sql);"
HOME.PHP
<?php
// define variables and set to empty values
$nameErr = $emailErr = $cityErr = $commentErr = $genderErr = "";
$name = $email = $city = $comment = $gender = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Please add a name";
} else {
$name = validateInput($_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 = "Please add an email";
} else {
$email = validateInput($_POST["email"]);
// check if email is an email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email format";
}
}
if (empty($_POST["city"])) {
$cityErr = "Please add your city";
} else {
$city = validateInput($_POST["city"]);
// check if city only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$city)) {
$cityErr = "Only letters and white space allowed";
}
}
if (empty($_POST["comment"])) {
$commentErr = "Please add your comment";
} else {
$comment = validateInput($_POST["comment"]);
// check if comment only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$comment)) {
$commentErr = 'Only "/", "-", "+", and numbers';
}
}
if (empty($_POST["gender"])) {
$genderErr = "Please pick your gender";
} else {
$gender = validateInput($_POST["gender"]);
}
}
// Validate Form Data
function validateInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["city"]) && !empty($_POST["comment"]) && !empty($_POST["gender"]))
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO info (name, email, city, comment, gender)
VALUES ('$name', '$email', '$city', '$comment', '$gender')";
// use exec() because no results are returned
$conn->exec($sql);
header("Location: welcome.php");
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>PHP Form</h2>
<p>Doesn't submit until the required fields you want are filled</p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="error">
<p><span>* required field</span></p>
<div><?php echo $nameErr;?></div>
<div><?php echo $emailErr;?></div>
<div><?php echo $cityErr;?></div>
<div><?php echo $commentErr;?></div>
<div><?php echo $genderErr;?></div>
</div>
<label for="name">Name:
<input type="text" name="name" id="name" placeholder="" value="<?php echo $name;?>">
<span class="error">*</span>
</label>
<label for="email">Email:
<input type="email" name="email" id="email" placeholder="" value="<?php echo $email;?>">
<span class="error">*</span>
</label>
<label for="city">city:
<input type="text" name="city" id="city" placeholder="" value="<?php echo $city;?>">
<span class="error">*</span>
</label>
<label for="comment">comment:
<input type="text" name="comment" id="comment" value="<?php echo $comment;?>">
<span class="error">*</span>
</label>
<label for="gender">Gender:<br>
<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">*</span>
</label>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
WELCOME.PHP
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=\, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Success! Form Submitted!</h1>
<script type="text/javascript" src="js/main.js" ></script>
</body>
</html>
you can do an array for Errors ,
$errors = []; // empty array
if(isset($_POST['username']) && empty($_POST['username'])) {
$errors['userName'] = "The userName is empty";
}
// then check if no errors , insert it to your DB :
if(count($errors) <= 0) {
// after filtering the username from XSS , insert it to DB.
}else {
// If there are ERRORS , even if one error :
foreach($errors as $error) {
// you can print all your errors
}
}
// or use then in onther place like this :
if(isset($errors['username'])) {
echo $erros['username'];
}
or you can use JavaScript xmlHttpRequest ,
READ about preventDefault function,
You can stop the form with this function:
$("form").submit(function(a){
a.preventDefault();
});