So I am trying to run this code and at the if (isset($_POST["Submit1"])) statement for isset, the form will not give the error message whenever I leave my form empty. It is supposed to give the $nameErr whenever the form is left empty, but it is not giving that error message. Whenever I delete the if (isset($_POST["Submit1"])) statement, it will run the else statement fine.
if (isset($_POST["Submit1"]))
{
if (isset($_POST['name']))
{
$name = sanitizeString($_POST['name']);
} else {
$nameErr = "* Your name must consist of letters and whitespace.";
}
}
Here is the submit button code.
<input type="submit" name="Submit1" value="Calculate">
As you can see, the names are the same so I don't think that is the problem.
Here is the rest of my code if you wish to take a look.
<!DOCTYPE html>
<html lang="en">
<head>
<title>GPA Improvement Calculator</title>
<style>
.error {
color: #FF0000;
}
</style>
</head>
<body>
<h1>GPA Improvement Calculator</h1>
<p><span class="error">All form fields must be completed for the GPA calculator to function.</span></p>
<?php
function sanitizeString($var)
{
$var = stripslashes($var);
$var = strip_tags($var);
$var = htmlentities($var);
return $var;
}
$name = "";
$nameErr = "";
if (isset($_POST["Submit1"]))
{
if (isset($_POST['name']))
{
$name = sanitizeString($_POST['name']);
} else {
$nameErr = "* Your name must consist of letters and whitespace.";
}
}
?>
<form method="post" action="improveGPA.php">
Name: <input type="text" size="35" name="name" value="<?php echo $name; ?>">
<span class="error"><?php echo $nameErr; ?></span>
<br><br>
E-mail: <input type="text" size="35" name="email" value="">
<span class="error"></span>
<br><br>
<input type="checkbox" name="agree" >
I agree to the terms and conditions of this website.
<span class="error"></span>
<br><br>
Current GPA: <input type="text" size="4" name="currentGPA" value="">
<span class="error"></span>
<br><br>
Current Total Credits: <input type="text" size="3" name="currentCredits" value="">
<span class="error"></span>
<br><br>
I am taking <input type="text" size="3" name="newCredits" value="">
<span class="error"></span> credits this semester.
If I want to raise my GPA
<input type="text" size="4" name="GPAincrease" value="">
<span class="error"></span> points,
I need a <span style="font-weight: bold;">????</span> GPA on my courses this semester.
<br><br>
<input type="submit" name="Submit1" value="Calculate">
</form>
</body>
</html>
It will only start messing up if I have that one if statement in and just won't show that error message at all, when the form is empty or filled in.
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>
I'm basically trying to
Get the form validated
Redirect to a success page (response.php) if validated
My Form's HTML. It's just a feedback form with sticky PHP.
<form method="post" action="">
<fieldset>
<legend>Contact Form</legend>
<label>Name (Required)</label>
<input name="name" type="text" placeholder="Enter your name. (e.g. Arthur)" value="<?php if(isset($_POST['name'])) echo htmlspecialchars($_POST['name']);
?>">
<span class="err"><?php echo $nameErr;?></span>
<label>Email (Required)</label>
<input name="email" type="email" placeholder="Enter a valid e-mail. (e.g. someone#host.com)" value="<?php if(isset($_POST['email'])) echo htmlspecialchars($_POST['email']);
?>">
<span class="err"><?php echo $emailErr;?></span>
<?php
if (isset($_POST['reason']))
{
$reasonVar = $_POST['reason'];
}
?>
<label>Reason</label>
<select name="reason">
<option <?php if($reasonVar=="question") echo 'selected="selected"'; ?> value="question">Question</option>
<option <?php if($reasonVar=="feedback") echo 'selected="selected"'; ?> value="feedback">Feedback</option>
<option <?php if($reasonVar=="suggestions") echo 'selected="selected"'; ?> value="suggestions">Suggestions</option>
<option <?php if($reasonVar=="other") echo 'selected="selected"'; ?> value="other">Other</option>
</select>
<label>Message (Required)</label>
<textarea name="message" placeholder="Enter your message. (e.g. Your website is awesome!)" ><?php if(isset($_POST['message'])) echo htmlspecialchars($_POST['message']);?></textarea>
<span class="err"><?php echo $messageErr;?></span>
<input class="sub" name="submit" type="submit" value="Submit">
</fieldset>
</form>
Here is the PHP for the page. It's just doing basic validations on the form, and attempting to use the header function to redirect the page to response.php after all the validation is successful (hence the long if statement).
<?php
$nameErr = $name = "";
$emailErr = $email ="";
$messageErr = $message ="";
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty(trim($_POST["name"]))){
$nameErr="Missing";
}
else{
$name = $_POST["name"];
}
if(empty(trim($_POST["email"]))){
$emailErr = "Missing";
}
elseif(!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid";
}
else{
$email=$_POST["email"];
}
if(empty(trim($_POST["message"]))){
$messageErr="Missing";
}
else{
$message = $_POST["message"];
}
if(!empty(trim($_POST["name"]))&&!empty(trim($_POST["email"]))&&filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)&&!empty(trim($_POST["message"]))){
header("Location:response.php");
exit;
}
}
?>
Right now, if the form validates, the form just disappears and I'm stuck on the form page without redirecting to the success page. I'm very new to backend web coding so any help would be greatly appreciated. Thank you so much in advance!
Here's my code:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["yourname"])) {
$yournameErr = "Name is required";
} else {
$yourname = test_input($_POST["yourname"]);
}
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["message"])) {
$messageErr = "Message is required";
} else {
$message = test_input($_POST["message"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
I have got to the point where it doesn't show errors but I probably didn't explain myself too clearly. After the point at which it doesn't show error messages anymore, I would like the form to no longer appear and then I can put something down like "Successful." However I can't seem to achieve this.
my form is :
<form action="contact.php" name="Form1" id="Form1" method="post">
<div>
<label>Your Name:</label>
<br />
<input type="text" name="yourname" id="yourname" placeholder="Full Name"
style="border:1; border-color:#000000; " />
<span class="error">* <?php echo $yournameErr;?></span>
</div>
<br />
<br />
<div>
<label> Email :</label> <br />
<input name="email" type="text" id="email" size="20" placeholder="Email"
style="border:1; border-color:#000000; " />
<span class="error">* <?php echo $emailErr;?></span>
</div>
<br />
<br />
<div>
<label> Subject : </label><br />
<input name="subject" type="text" id="subject" size="20" placeholder="Subject"
style="border:1; border-color:#000000; " />
</div>
<br />
<br />
<div>
<label> Message :<br /> </label>
<textarea rows="5" cols="40" name="message" type="text" id="message"
placeholder="The message you want to send to us." style="border:1; border-
color:#000000 " >
</textarea>
<span class="error">* <?php echo $messageErr;?></span>
</div>
<br />
<br />
<div>
<input type="submit" name="button" id="button" style="border:1; border-
color:#999999; " value="SEND"/>
</div>
</form>
What if you put your errors in an array and put a condition that check that array size and if it is 0 (no errors) echo the success message and don't show the form else join the errors and print it out.
Maybe like this:
contact.php
<?php
$error = array();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["yourname"])) {
$error['name'] = "Name is required";
} else {
$yourname = test_input($_POST["yourname"]);
}
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["message"])) {
$error['message'] = "Message is required";
} else {
$message = test_input($_POST["message"]);
}
if (!count($error)) {
$noError = true;
}
}
$successMessage = isset($noError) ? 'Successful.' : '';
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function getErrorMessage($type, $error)
{
return isset($error[$type]) ? $error[$type] : '';
}
if ($successMessage) {
echo $successMessage;
} else {
?>
<form action="contact.php" name="Form1" id="Form1" method="post">
<div>
<label>Your Name:</label>
<br/>
<input type="text" name="yourname" id="yourname" placeholder="Full Name"
style="border:1px; border-color:#000000; "/>
<span class="error">* <?php echo getErrorMessage('name', $error); ?></span>
</div>
<br/>
<br/>
<div>
<label> Email :</label> <br/>
<input name="email" type="text" id="email" size="20" placeholder="Email"
style="border:1px; border-color:#000000; "/>
<span class="error">* <?php echo getErrorMessage('email', $error); ?></span>
</div>
<br/>
<br/>
<div>
<label> Subject : </label><br/>
<input name="subject" type="text" id="subject" size="20" placeholder="Subject"
style="border:1px; border-color:#000000; "/>
</div>
<br/>
<br/>
<div>
<label> Message :<br/> </label>
<textarea rows="5" cols="40" name="message" type="text" id="message"
placeholder="The message you want to send to us." style="border:1px; border-
color:#000000 "></textarea>
<span class="error">* <?php echo getErrorMessage('message', $error); ?></span>
</div>
<br/>
<br/>
<div>
<input type="submit" name="button" id="button" style="border:1px; border-
color:#999999; " value="SEND"/>
</div>
</form>
<?php } ?>
According to your code, I'm going to assume that your contact.php is posting to itself. In other words, your PHP code is located above your HTML --as a result of your question that the contact form no longer renders after a request. That is, once the server renders the page, the form tag will not display because there are no errors in the submission or the super global $_POST has been set.
I've slightly altered your code for readability. I included an array that will hold all your error messages throughout your form validation. If there are no errors, then we can simulate a successful submission and thus reflect this result on response. Your form will only display if there are errors OR the post has not been submitted.
Inside your form, you need an input tag of submit. Furthermore, only if errors are indeed set, that we want to display an error specific message. That is why a condition is set for your span tags. Lastly, I included the same condition in your values -an additional feature for remembering what you have entered.
If the form is successfully submitted, then don't render the form tag and, instead, display a message of success along with all the POST data!
<?php
if (isset($_POST['submit'])) {
$error_message = array();
if (empty($_POST["yourname"])) {
$error_message['yournameErr'] = "Name is required";
} else {
$yourname = test_input($_POST["yourname"]);
}
if (empty($_POST["email"])) {
$error_message['emailErr'] = "Email is required";
} elseif (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $_POST["email"])) {
$error_message['emailErr'] = "Invalid email format";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["message"])) {
$error_message['messageErr'] = "Message is required";
} else {
$message = test_input($_POST["message"]);
}
if(empty($error_message)) {
// process data from post
$successful = true;
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<?php if(!empty($error_message) || !isset($_POST['submit'])) : ?>
<form action="contact.php" name="Form1" id="Form1" method="post">
<div>
<label>Your Name:</label>
<br />
<input type="text" name="yourname" id="yourname" placeholder="Full Name"
style="border:1; border-color:#000000; " value="<?php if(isset($yourname)) {echo $yourname; }?>" />
<span class="error">* <?php if(isset($error_message['yournameErr'])){echo $error_message['yournameErr']; }?></span>
</div>
<br />
<br />
<div>
<label> Email :</label> <br />
<input name="email" type="text" id="email" size="20" placeholder="Email"
style="border:1; border-color:#000000; " value="<?php if(isset($email)) { echo $email;}?>" />
<span class="error">* <?php if(isset($error_message['emailErr'])) {echo $error_message['emailErr'];}?></span>
</div>
<br />
<br />
<div>
<label> Subject : </label><br />
<input name="subject" type="text" id="subject" size="20" placeholder="Subject"
style="border:1; border-color:#000000; " />
</div>
<br />
<br />
<div>
<label> Message :<br /> </label>
<textarea rows="5" cols="40" name="message" type="text" id="message" placeholder="The message you want to send to us." style="border:1; border-color:#000000"></textarea>
<span class="error">* <?php if(isset($error_message['messageErr'])) {echo $error_message['messageErr']; }?></span>
<br>
<input type="submit" name="submit" value="Submit">
</div>
<?php endif; ?>
<?php if(isset($successful)) : ?>
<p>Successful</p>
<p>Your name: <?=$yourname;?></p>
<p>Your email: <?=$email;?></p>
<p>Your subject: <?=$_POST['subject']?></p>
<p>Your message: <?=$message;?></p>
Back to form
<?php endif; ?>
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();
});