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