PHP Form Data Validation is not working - php

Hi I'm trying to do a form with data validation before writing into database. But im not sure why the data validation is not working. Below is my codes
filename: bookoffer.php
$NameErr = $EmailErr = $DescriptionErr = "";
//$Name = $Email = $Description;
if (isset($_POST['Submit']))
{
$errors = array();
if (empty($_POST['Name']))
{
$NameErr = "**Name is required**";
}
else
{
$Name = ($_POST['Name']);
//check if name only contain letter and white space
if (!preg_match("/^[a-zA-Z ]*$/",$Name))
{
$NameErr = "**Only letters and white space allowed**";
}
}
if (empty($_POST['Email']))
{
$EmailErr = "**Email is required**";
}
else
{
$Email = ($_POST['Email']);;
//check if e-mail address is well-formed
if (!filter_var($Email, FILTER_VALIDATE_EMAIL))
{
$EmailErr = "**Invalid email format**";
}
}
if (empty($_POST['Description']))
{
$Description = "**Description is required**";
}
else
{
$Description = ($_POST['Description']);
}
}
//if(count($errors)==0)
include 'database_connect.php'; //make database connection
$Name = $_POST['Name'];
$Email = $_POST['Email'];
$Description = $_POST['Description'];
$sql = "INSERT INTO books_offer (Name, Email, Description) values ('$Name', '$Email', '$Description')";
$redirect = true;
header('Location: Thank_you.php');
mysqli_query($conn, $sql) or die (mysqli_error($conn));
mysqli_close($conn);
?>
Here is the html file which is calling for bookoffer.php
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>Please Offer Your Book</h2>
<form id="bookoffer" method="post" action="bookoffer.php" >
<p><span class="error"> <font color="red">*required field.</font></span></p>
Name<font color="red">*</font> <input type="text" name="Name" >
<span class="error"> <?php echo $NameErr;?></span>
<br></br>
Email<font color="red">*</font> <input type="text" name="Email" >
<span class="error"> <?php echo $EmailErr;?></span>
<br></br>
Description<font color="red">*</font><textarea name ="Description" rows="5" cols="40" ></textarea>
<span class="error"> <?php echo $DescriptionErr;?></span>
<br></br>
<input type="submit" name="submit_form" value="Submit" />
</form>
</body>
</html>

You're not populating your $errors array so the if statement you've commented out will always be true. You are storing your errors in individual variables. One option would be to change
$errors = array();
to
$errors = false;
then, when you are setting the error variables add a line to each one to set $errors to true, one example,
if (empty($_POST['Name']))
{
$NameErr = "**Name is required**";
$errors = true; // this line added
}
You can now update your commented out if statement to
if ($errors) {

Related

Unable to throw error Message

registration_form
<!DOCTYPE HTML>
<html>
<head>
<title>Register</title>
</head>
<body>
<form action="" method="POST">
Name:
<input type="text" name="name">
<br/> <br/>
Username:
<input type="text" name="username">
<br/> <br/>
Password:
<input type="password" name="password">
<br/> <br/>
Email:
<input type="text" name="email">
<br/> <br/>
<input type="submit" name="submit" value="Register">
</form>
</body>
</html>
<?php
require('connect.php');
require('validation.php');
$name = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if(isset($_POST["submit"])){
if($query = mysqli_query($connect,"INSERT INTO users
(`id`,`name`,`username`, `password`, `email`) VALUES ('','".$name."',
'".$username."', '".$password."', '".$email."')")){
echo "Success";
}else{
echo "Failure" . mysqli_error($connect);
}
}
?>
validation.php
<?php
// define variables and set to empty values
$nameErr = $emailErr = $userErr = $passwordErr = "";
$name = $email = $username =$password = "";
if (isset($_POST['submit'])) {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["username"])) {
$userErr = "Username is required";
} else {
$username = test_input($_POST["username"]);
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password= test_input($_POST["password"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
connect.php
<?php
$connect = mysqli_connect("localhost", "root", "","php_forum")
or die("Error " . mysqli_error($connect));
?>
I'm developing a simple Registration from with four inputs i.e., Name, username, password, email.when the user fills out the form and click submit button then all the filled data should go n save in data base which is working fine in my case, but when the user wont fill any data and if user simply clicks a submit button then error message should be shown like "ALL FIELDS ARE NECESSARY", but where in my case even if i click submit button without entering any values the mesage i'm getting as success and all the null values are getting stored in the data base which should not happen, my output should be if i fill the forms n click submit button then all the data should be stored in database and if i click submit button without filling out any value then error should throw that "all field to be filled" and no null value should be stored in data base, please can any one guide me what changes i should do so that to get my desired output.
You do
require('validation.php');
setting and checking alot of variables e.g.
$name = test_input($_POST["name"]);
$nameErr = "Only letters and white space allowed";
come back from require and overwrite $name with original posted values and do nothing with $nameErr
$name = $_POST['name'];
check the errors after the require
e.g.
require('validation.php');
$lsError = $nameErr . $emailErr . $userErr . $passwordErr;
if(trim($lsError) != '') {
echo $lsError ."<BR>";
echo "ALL FIELDS ARE NECESSARY";
}
else {
//rest of your insert
}

how to throw validation error

registration_from.php
<!DOCTYPE HTML>
<html>
<head>
<title>Register</title>
</head>
<body>
<form action="" method="POST">
Name:
<input type="text" name="name">
<br/> <br/>
Username:
<input type="text" name="username">
<br/> <br/>
Password:
<input type="password" name="password">
<br/> <br/>
Email:
<input type="text" name="email">
<br/> <br/>
<input type="submit" name="submit" value="Register">
</form>
</body>
</html>
<?php
require('connect.php');
require('validation.php');
$name = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if(isset($_POST["submit"])){
if($query = mysqli_query($connect,"INSERT INTO users
(`id`,`name`,`username`, `password`, `email`) VALUES ('','".$name."',
'".$username."', '".$password."', '".$email."')")){
echo "Success";
}else{
echo "Failure" . mysqli_error($connect);
}
}
?>
validation.php
<?php
// define variables and set to empty values
$nameErr = $emailErr = $userErr = $passwordErr = "";
$name = $email = $username =$password = "";
if (isset($_POST['submit'])) {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["username"])) {
$userErr = "Username is required";
} else {
$username = test_input($_POST["username"]);
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password= test_input($_POST["password"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
connect.php
<?php
$connect = mysqli_connect("localhost", "root", "","php_forum")
or die("Error " . mysqli_error($connect));
?>
I'm developing a simple Registration from with four inputs i.e., Name, username, password, email.when the user fills out the form and click submit button then all the filled data should go n save in data base which is working fine in my case, but when the user wont fill any data and if user simply clicks a submit button then error message should be shown like "ALL FIELDS ARE NECESSARY", but where in my case even if i click submit button without entering any values the mesage i'm getting as success and all the null values are getting stored in the data base which should not happen, my output should be if i fill the forms n click submit button then all the data should be stored in database and if i click submit button without filling out any value then error should throw that "all field to be filled" and no null value should be stored in data base, please can any one guide me what changes i should do so that to get my desired output.
If you don't mind adding a little more code, you code do like:
In your registration_form.php
<?php
require('validation.php'); // Require first to do validation before queries
require('connect.php');
// Remove the part where you set variables to $_POST params
// Variables are already set inside validation.php
/**
* Then, I recommend moving queries to **connect.php**
* to have all your sql functions inside one file.
* Also moving the inserting of data to a function for easy grouping/calling
*/
if (isset($_POST["submit"]) {
// Check if validation does not fail
if ($emailErr == "" || $nameErr == "" || $userErr == "" || $passwordErr == "") {
// Call to insert function
doInsert($name, $email, $username, $password);
} else {
echo $emailErr . " " . $nameErr . " " . $userErr . " " . $passwordErr;
}
}
?>
In your connect.php
function doInsert($name, $email, $username, $password) {
$connect = mysqli_connect("localhost", "root", "","php_forum")
or die("Error " . mysqli_error($connect));
$sql = "INSERT INTO users(`id`,`name`,`username`, `password`, `email`)
VALUES ('','".$name."', '".$username."', '".$password."', '".$email."')";
$query = mysqli_query($connect, $sql);
if ($query) {
echo "Success";
} else {
echo "Failure " . mysqli_error($connect);
}
}
Please add error in session and print session in form file.
In validation.php
$nameErr = $emailErr = $userErr = $passwordErr = "";
$name = $email = $username =$password = "";
if (isset($_POST['submit'])) {
$name = $_POST["name"];
$email = $_POST["email"];
$username = $_POST["username"];
$password = $_POST["password"];
if($name == '' || $email == '' || $username == '' || $password == "")
{
echo "ALL FIELDS ARE NECESSARY";
exit();
}
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["username"])) {
$userErr = "Username is required";
} else {
$username = test_input($_POST["username"]);
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password= test_input($_POST["password"]);
}
}
registration_from.php
if(isset($_SESSION['error]) && !empty($_SESSION['error])){
echo $_SESSION["error"]
}
<?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;
?>

validation form using php code

Hi i am trying to build a form and insert the data to my db it's working perfect now i want to make it validation using php to prevent span inputs i am beginner at php so p;ease i need help with this
and the php code
<?php
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$con = mysqli_connect('localhost','root','');
if(!$con)
{echo'not connect';}
if(!mysqli_select_db($con,'form'))
{echo'not selected';}
$name=$_POST['name'];
$phone=$_POST['phone'];
$nationality=$_POST['nationality'];
$country=$_POST['country'];
$sql = "INSERT INTO newform(Name,Number,Nationality,Country) VALUES('$name','$phone','$nationality','$country')";
if(!mysqli_query($con,$sql))
{echo'not insert';}
else
{
echo'insertes';
}
header("refresh:2;url=form.php");
?>
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
$error = false;
$nameErr = $phoneErr = $nationalErr = $countErr = "";
$con = mysqli_connect('localhost','root','');
if(!$con)
{
echo 'not connect';
}
if(!mysqli_select_db($con,'form'))
{
echo' DB not selected';
}
if(isset($_POST['submit'])){
$name=$_POST['name'];
$phone=$_POST['phone'];
$nationality=$_POST['nationality'];
$country=$_POST['country'];
if($name ==""){
$error = true;
$nameErr = "Name field is empty";
}
if($phone ==""){
$error = true;
$phoneErr = "phone field is empty";
}
if($nationality ==""){
$error = true;
$nationalErr = "nationality field is empty";
}
if($country ==""){
$error = true;
$countErr = "country field is empty";
}
if($error == false){
$sql = "INSERT INTO newform(Name,Number,Nationality,Country) VALUES($name,$phone,$nationality,$country')";
if(!mysqli_query($con,$sql))
{
echo 'Values not insert';
}else
{
header("refresh:2;url=form.php");
}
}
}
?>
<form method="post">
First name:<br>
<input type="text" name="name">
<p style="color:red"><?php echo $nameErr ?></p>
<br>
phone:<br>
<input type="text" name="phone">
<p style="color:red"><?php echo $phoneErr ?></p>
<br><br>
Nationality:<br>
<input type="text" name="nationality">
<p style="color:red"><?php echo $nationalErr ?></p>
<br><br>
Country:<br>
<input type="text" name="country">
<p style="color:red"><?php echo $countErr ?></p>
<br><br>
<input type="submit" value="Submit" name="submit">
</form>
</body>

Insert data from a form with required fields

Please i need help with this form i have those problems Please help me
1- When it submit write error but i see in PHPMyAdmin it's added and record in MySql Database
Example:
Error: INSERT INTO clients (name, email, website, comment, gender) VALUES ('', '', '', '', '')
2- When i don't fill and a required field i see the error message but it's added and record in MySql Database
Example
Email is required
my code is below
<?php
// Database information
$servername = "localhost";
$username = "mymbnwye_mexx";
$password = "";
$dbname = "";
// Database connection
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);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
// Check input
function checker_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// 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 {
$name = checker_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = checker_input($_POST["email"]);
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = checker_input($_POST["website"]);
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = checker_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = checker_input($_POST["gender"]);
}
$sql = "INSERT INTO clients (name, email, website, comment, gender)
VALUES ('$name', '$email', '$website', '$comment', '$gender')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
<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 $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></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
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
This should work 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>
using code that you have mentioned, your sql query will always execute event if there is empty fields because you are writing your query outside of condition.
This code will help solving your problem
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$name = checker_input($_POST["name"]);
$gender = checker_input($_POST["gender"]);
$comment = empty($_POST["comment"]) ? "" :checker_input($_POST["comment"]);
$website = empty($_POST["website"]) ? "" :checker_input($_POST["website"]);
$email = checker_input($_POST["email"]);
$sql = "INSERT INTO clients (name, email, website, comment, gender)
VALUES ('$name', '$email', '$website', '$comment', '$gender')";
if ($conn->query($sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
Your code doesn't stop the query being executed if there are missing values. Try something like this instead:
function ValuesCompleted()
{
$values = Array('name', 'email', 'gender');
foreach($values as $index)
{
if(empty($_POST[$index]))
{
return "{$index} not supplied";
}
}
return true;
}
if(isset($_POST) && ValuesCompleted() === true)
{
try
{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$statement = $conn->prepare("INSERT INTO clients (name, email, website, comment, gender)
VALUES (?, ?, ?, ?, ?)");
$statement->execute(Array($_POST['name'], $_POST['email'], $_POST['website'], $_POST['comment'], $_POST['gender']);
$conn = null;
}
catch(PDOException $e)
{
// ideally you would print this to a log, not echo it.
echo($e->getMessage());
}
}
else
{
echo ValuesCompleted();
}

Introducing Data in a postgresql database from a php form & Validating the data in the form

I have a from to introduce the data and I'm trying to validate the data. However, either the data is introduced or not, the info is introduce in the database.
For example, If I leave the name blank, I get an error message that the name cannot be blank, but the blank name is introduce in the database.
How can I do, so only after all the fields have been validated, the data is introduce in the database?
Thank you so much
CODE
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $surnameErr = "";
$name = $email = $surname = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["surname"])) {
$surname = "";
} else {
$surname = test_input($_POST["surname"]);
}
}
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 $nameErr;?></span>
<br><br>
Last Name: <input type="text" name="surname">
<span class="error"><?php echo $surnameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></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 $surname;
echo "<br>";
?>
<?php
$db = pg_connect('host=localhost dbname=postgres user=myusername password=mypassword');
$firstname = pg_escape_string($_POST['name']);
$surname = pg_escape_string($_POST['website']);
$emailaddress = pg_escape_string($_POST['email']);
$query = "INSERT INTO friends(firstname, surname, emailaddress) VALUES('" . $firstname . "', '" . $surname . "', '" . $emailaddress . "')";
$result = pg_query($db, $query);
if (!$result) {
$errormessage = pg_last_error();
echo "Error with query: " . $errormessage;
exit();
}
printf ("These values were inserted into the database - %s %s %s", $firstname, $surname, $emailaddress);
pg_close();
?>
</body>
</html>

Categories