validation form using php code - php

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>

Related

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;
?>

How to validate PHP Form input and database submittion

Am just getting my hand on php and I need some little help please. I am working on a registration form with server-side validation, then after validation, the form input should be submitted to the database. I entered data, click submit button, but the data were not submitted to the database. There is no error message. I like you to help me point out where have been wrong and give me a possible solution. Thanks.
Index.php
<?php
include ('signup.php');
?>
<div class="maindiv">
<div class="login"></div>
<div class="wrapper">
<div class="pageintro">
<p>PHP</p>
<p>PROJECT 1</p>
</div>
<div class="regform">
<form name="reg" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" >
<p class="regformp">Fill all Fields</p>
<div class="regwrap">
<div class="inp">Full Name</div>
<div class="inp1"><input type="text" name="FullName" value="<?php echo $FullName; ?>"></div>
<span class="error"><?php echo $fullnameErr;?></span>
<div class="inp">E-Mail</div>
<div class="inp1"><input type="text" name="Email" value="<?php echo $Email; ?>"></div>
<span class="error"><?php echo $emailErr;?></span>
<div class="inp">Password</div>
<div class="inp1"><input type="password" name="Password"></div>
<span class="error"><?php echo $passwordErr;?></span>
<div class="inp">Confirm Password</div>
<div class="inp1"><input type="password" name="ConfirmPassword"></div>
<span class="error"><?php echo $conpasswordErr;?></span>
<div class="inp">Gender</div>
<div class="inp1"><input type="radio" name="Gender" value="Male" <?php if(isset($Gender)&& $Gender=="Male") echo "checked"; ?> >Male <input type="radio" name="Gender" <?php if(isset($Gender)&& $Gender=="Female") echo "checked"; ?> Value="Female">Female</div>
<span class="error"><?php echo $genderErr;?></span>
<div class="inp">Date Of Birth</div>
<div class="inp1"><select name="DayOfBirth"><option>01</option>
<option>02</option>
<option>03</option>
<option>04</option>
<option>05</option></select> <select name="MonthOfBirth"><option>Jan</option>
<option>Feb</option>
<option>Mar</option>
<option>Apr</option>
<option>May</option></select> <select name="YearOfBirth"><option>1970</option>
<option>1971</option>
<option>1972</option>
<option>1973</option>
<option>1974</option></select></div>
<span class="error"><?php echo $dobErr;?></span>
<span class="error"><?php echo $mobErr;?></span>
<span class="error"><?php echo $yobErr;?></span>
<div class="inp2"><input type="submit" name="submit" value="SIGN UP"></div></div>
</form>
signup.php
<?php
include ('project1db.php');
//Define variables
$fullnameErr="";
$emailErr="";
$passwordErr="";
$conpasswordErr="";
$genderErr="";
$dobErr="";
$mobErr="";
$yobErr="";
$FullName="";
$Email="";
$Password="";
$ConfirmPassword="";
$Gender="";
$DayOfBirth="";
$MonthOfBirth="";
$YearOfBirth="";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["FullName"])){
$fullnameErr = "Name is required";
}
else{
$FullName = test_input($_POST["FullName"]);
//Check if name only contains letters and whitespace
if(!preg_match("/^[a-zA-Z]*$/",$FullName)){
$fullnameErr = "Enter Valid name please!";
}
}
if(empty($_POST["Email"])){
$emailErr = "Email is required";
}else{
$EMail = test_input($_POST["Email"]);
//Check if e-mail address is correct
if(!filter_var($EMail, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email address";
}
}
if(empty($_POST["Password"])){
$passwordErr = "Password is required";
}else{
$Password = test_input($_POST["Password"]);
//Check password
if(!preg_match("/^[a-z0-9]{6,}$/",$Password)){
$passwordErr = "Password should contain 6+ characters, lowercase and numbers!";
}
}
if(empty($_POST["ConfirmPassword"])){
$conpasswordErr = "Confirm your Password!";
}
else{
$ConfirmPassword = test_input($_POST["ConfirmPassword"]);
//Confirm if password match
if($ConfirmPassword != $Password){
$conpasswordErr = "Password not match!";
}
}
if(empty($_POST["Gender"])){
$genderErr = "Select your Gender!";
}else{
$Gender = test_input($_POST["Gender"]);
}
if(empty($_POST["DayOfBirth"])){
$dobErr = "Select your Day Of Birth";
}else{
$DayOfBirth = test_input($_POST["DayOfBirth"]);
}
if(empty($_POST["MonthOfBirth"])){
$mobErr = "Select your Month Of Birth";
}else{
$MonthOfBirth = test_input($_POST["MonthOfBirth"]);
}
if(empty($_POST["YearOfBirth"])){
$yobErr = "Select your Year Of Birth";
}else{
$YearOfBirth = test_input($_POST["YearOfBirth"]);
}
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if($fullnameErr = $emailErr = $passwordErr = $conpasswordErr = $genderErr = $dobErr = $mobErr = $yobErr = ""){
$sql = "INSERT into usersignup (FullName, Email, Password, Gender, DayOfBirth, MonthOfBirth, YearOfBirth) VALUES(?,?,?,?,?,?,?)";
if($stmt = $conn->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("ssssisi", $FullName, $Email, $Password, $Gender, $DayOfBirth, $MonthOfBirth, $YearOfBirth);
/* Set the parameters values and execute
the statement again to insert another row */
$FullName = $_REQUEST['FullName'];
$Email = $_REQUEST['Email'];
$Password = $_REQUEST['Password'];
$Gender = $_REQUEST['Gender'];
$DayOfBirth = $_REQUEST['DayOfBirth'];
$MonthOfBirth = $_REQUEST['MonthOfBirth'];
$YearOfBirth = $_REQUEST['YearOfBirth'];
$stmt->execute();
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not prepare query: $sql. " . $conn->error;
}
// Close statement
$stmt->close();
// Close connection
$conn->close();
}
else{
}
?>
Database Connection
project1db.php
<?php
$dbhost = 'localhost:3308';
$dbuser = 'root';
$dbpass = '';
$dbname = 'phpproject';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(!$conn )
{
die('Could not connect: '.mysqli_error());
}
echo 'Connected successfully';
I have figured out the problem and the problem have been solved.
First problem is with the Mysql database. The AutoIncrement colunm precisely was not set to AutoIncrement. So, I open PhpMyadmin to alter and set the Id colunm to AutoIncrement.
Second Problem was with the conditional statement here:
if($fullnameErr = $emailErr = $passwordErr = $conpasswordErr = $genderErr = $dobErr = $mobErr = $yobErr = "")
The correct line of code which later worked properly is:
if(empty($fullnameErr) && empty($emailErr) && empty($passwordErr) && empty($conpasswordErr) && empty($genderErr) && empty($dobErr) && empty($mobErr) && empty($yobErr))
This is an important information for those who got confused after they have validated the data input but didn't know how to save the data into the database table.

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

PHP Form Data Validation is not working

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) {

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