PHP Validation Form Not Showing in Localhost? - php

There is no logical error, I think Just the syntax error, also this was not returning any value or something.
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$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>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<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
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
[enter image description here][1]enter code here
[1]: https://i.stack.imgur.com/H4Sdy.jpg**strong text**

JUST USE DOT. PHP Extension at the last that will resolve our issue.
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$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>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<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
<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 $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>

You just had a space between < and php on line 45, also make sure the extension of your file is .php
try this
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$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>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<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
<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 $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>

Related

PHP Form Validation and showing error message beside Input Fields

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>

PHP page won't produce output from php page with $_SERVER == "POST" method

I put together a code to get the output to show up on the same page as the php page but it won't show. What was done wrong? I am not sure why. I made sure this was run on the web browser to see if outcome will show, but it did not.
Here is source code:
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST ["name"]);
$email = test_input($_POST ["email"]);
$website = test_input($_POST ["website"]);
$comment = test_input($_POST ["comment"]);
$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>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name"> <br>
<br> E-mail: <input type="text" name="email"> <br>
<br> Website: <input type="text" name="website"> <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 <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 $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>

nothing happens after clicking submit button

I can not figure out what i missed here in my code. i if else statement is working because i can see my form and after submitting i suppose to see message after tag. How would i know if submit button is respond or not.
<?php
$output_form = true;
$fname = "";
$lname = "";
$address1 ="";
$address2 ="";
$city = "";
$state = "";
$zipcode = "";
if (isset($_POST['submit'])) {
print_r($_POST);
$fname = trim($_POST["firstName"]);
$lname = trim($_POST['lastName']);
$address1 = trim($_POST['address1']);
$address2 = trim($_POST['address2']);
$city = trim($_POST['city']);
$state = trim($_POST['state']);
$zipcode = trim($_POST['zipcode']);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Assignment 3 </title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<?php
if ($output_form) {
?>
<h1>Enter your information</h1>
<form name="userform" action="<?= $_SERVER['PHP_SELF'] ?>" method="post">
<p>First Name: <input name="firstName" type="text" value="<?= $fname ?>"></p>
<p>Last Name: <input name="lastName" type="text" value="<?= $lname ?>"></p>
<p>Address 1: <input name="address1" type="text" value="<?= $address1 ?>"></p>
<p>Address 2: <input name="address2" value="<?= $address2 ?>" type="text" ></p>
<p>City: <input name="city" type="text" value="<?= $city ?>"></p>
<p>State: <input name="state" type="text" value="<?= $state ?>"></p>
<p>Zip Code: <input name="zipcode" type="number" value="<?= $zipcode ?>"></p>
<input class="button" name="submit" type="button" value="Button">
</form>
<?php
} else {
?>
<h2>Your information is:</h2>
<p class="result">
Name: <?= $fname.' '.$lname ?><br>
Street Address: <?= $address1 ?><br>
City, State: <?=$city.' '.$state ?>
</p>
<?php
}
?>
</body>
</html>
Make your input type submit
<input class="button" name="submit" type="button" value="Button">
Should be
<input class="button" name="submit" type="submit" value="Button">

How to connect page between signin,signup and profile in php

i'm still newbie in php, i want to connect this three page. I want to know how to tansfer data from signup to pfofile and also the sign in page. I tried to use tag but not working.
page=signup
<body>
<?php
// define variables and set to empty values
$email = $username = $name = $contact = $birthday = $gender = $address = $password = $payment ="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = test_input($_POST["email"]);
$username = test_input($_POST["username"]);
$name = test_input($_POST["name"]);
$contact = test_input($_POST["contact"]);
$birthday = test_input($_POST["birthday"]);
$gender = test_input($_POST["gender"]);
$address = test_input($_POST["address"]);
$password = test_input($_POST["password"]);
$payment = test_input($_POST["payment"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="login">
<form id="registeration" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<legend><h1>Registeration</h1></legend>
<p>Email:<br/>
<input type="email" name="email"></p>
<p>Username:<br/>
<input type="text" name="username" />
</p>
<p>Your Name:<br/>
<input type="text" name="name"/></p>
<p>Contact Number:<br/>
<input type="text" name="contact"/></p>
<p>Birthday:<br/>
<input type="date" name="birthday">
<p>Gender:<br/>
<input type="radio" name="gender" value="male"/>Male
<input type="radio" name="gender" value="female"/>Female
</p>
<p>Address: <br/>
<textarea name="address" cols="50"></textarea></p>
<p>Password:<br/>
<input name="password" type="password" size="50"/></p>
</p>
<h2>Choose payment method:<br/></h2>
<p><input type="radio" name="payment" value="cod"/>CASH ON DELIVERY</p>
<p><input type="radio" name="payment" value="Online Banking"/>ONLINE BANKING : CIMB Clicks<br/>
<p><input type="radio" name="payment" value="Online Banking"/>ONLINE BANKING : Maybank<br/>
<p><input type="radio" name="payment" value="Online Banking"/>ONLINE BANKING : BSN<br/>
<p><input type="radio" name="payment" value="atm"/>ATM</p>
<p><button type="submit" value="submit">Submit</button><span> <span><span><span><span>
<button type="reset" value="cancel">Cancel</button></p>
</fieldset>
</form>
</div>
echo $email;
echo "<br>";
echo $username;
echo "<br>";
echo $name;
echo "<br>";
echo $contact;
echo "<br>";
echo $birthday;
echo "<br>";
echo $gender;
echo "<br>";
echo $address;
echo "<br>";
echo $password;
echo "<br>";
echo $payment;
?>
</body>
page=signin
<body>
<div id="login">
<fieldset>
<legend><h1>Login</h1></legend>
<form id="signin" method="POST">
<p>Username:<br/>
<input type="text" name="username"/></p>
<p>Password:<br/>
<input type="password" name="password"/></p>
<p><button type="submit" value="submit">Submit</button><span>
<button type="reset" value="cancel">Cancel</button></p>
</form>
</fieldset>
<!-- end .content --></div>
<?php
error_reporting(0);
if (!empty ($_POST)){
if ($_POST ["username"] == NULL){
echo "Please insert your username!";}
else{
$strusername=$_POST["username"];
echo "<p>$strusername</p>";
}}
if (!empty ($_POST)){
if ($_POST ["password"] == NULL){
echo "Please insert the password!";}
else {
$strpassword=$_POST["password"];
echo "<p>$strpassword</p>";
}}
?>
</body>
page=profile
<body>
<div class="container">
<div class="content">
<table>
<td colspan="5"><b>PROFILE</b></td>
<tr>
<td><div align="left">Username:</div></td><td><?php echo $username ?></td></tr>
<td><div align="left">Name:</div></td><td><?php echo $name ?></td></tr>
<td><div align="left">Username:</div></td><td><?php echo $username ?></td></tr>
<td><div align="left">Birthday:</div></td><td><?php echo $birthday ?></td></tr>
<td><div align="left">Contact Number:</div></td><td><?php echo $contact ?></td></tr>
<td><div align="left">Gender:</div></td><td><?php echo $gender ?></td></tr>
<td><div align="left">Address:</div></td><td><?php echo $address ?></td></tr>
<td><div align="left">My payment Method:</div></td><td><?php echo $payment ?></td> </tr>
<tr>
<td><div align="left"><button type="submit" value="Edit Profile" >Edit Profile</button></div> </td>
</tr>
</table>
<!-- end .content --></div>
<!-- end .container --></div>
</body>
Well, Try to use the post and get.
The PHP superglobals $_GET and $_POST are used to collect form-data.The example below displays a simple HTML form with two input fields and a submit button:
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST method.
To display the submitted data you could simply echo all the variables. The "welcome.php" looks like this:
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>
The output could be something like this:
Welcome John
Your email address is john.doe#example.com
The same result could also be achieved using the HTTP GET method:
<html>
<body>
<form action="welcome_get.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
and "welcome_get.php" looks like this:
<html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?>
</body>
</html>
I Suggest you to follow this tutorial here
I hope it will help you, best regards
Use $_SESSION
In every page start with <?php session_start(); ?>
then store $_SESSION['email'] = test_input($_POST["email"]);
Then in any page you can use echo $_SESSION['email'];
You should use SESSION for simple login functionality....
refer this tutorial about basic login and functionality

I would like to know how to stop form submission when the validation fails?

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();
});

Categories