Validating html forms using php - php

I have a form which needs to be validated using php before inserting form values into a database.
it worked just fine if the fields are empty, however when I included a code to ensure only letters and white spaces are allowed in the first and last name fields it broke the validation process i.e. when I typed in any combinations of letters in the fields it displayed an error message saying "only letters and white spaces are required".
Secondly, when all fields are empty, the form displays the appropriate error message and does no submit the form to the database. However, when I type in a message in the textarea field with other fields empty, the form submits the data to the database as well as displays error messages for the other empty fields.
Any help to resolve these issues would be much appreciated.
Here is the code:
<?php
$fnameErr = $lnameErr = $emailErr = $amountErr = $phoneErr = $genderErr = $messageErr = $categoryErr = $countryErr = "";
$fname = $lname = $email = $amount = $phone = $gender = $message = $category = $country = "";
$ipaddress ="";
$defaultMessage = "Please type your message here.";
$formErrors = false;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//for first name
$name= $_POST["fname"];
if (empty($_POST["fname"])){
$fnameErr = "Please, enter your first name";
$formErrors = true;
}elseif(!preg_match("/^[a-zA-Z]*&/", $name)){
$fnameErr = "Only letters and white spaces are allowed in the first name field";
$formErrors = true;
}else{
$fname = $_POST["fname"];
$formErrors = false;
}
//Last Name match
// for last name
$name2= $_POST["lname"];
if (empty($_POST["lname"])){
$lnameErr = "Please, enter your last name";
$formErrors = true;
}elseif(!preg_match("/^[a-zA-Z]*&/", $name2)){
$lnameErr = "Only letters and white spaces are allowed in the Last name field";
$formErrors = true;
}else{
$lname = $_POST["lname"];
$formErrors = false;
}
// for email format
$emailf =($_POST["email"]);
if (empty($_POST["email"])) {
$emailErr = "Please, enter your email";
$formErrors = true;
}elseif (!filter_var($emailf, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
$formErrors = true;
}else {
$email = $_POST["email"];
$formErrors = false;
}
//for phone
if (empty($_POST["phone"])){
$phoneErr = "Please, enter your phone number";
$formErrors = true;
}else{
$phone = $_POST["phone"];
$formErrors = false;
}
// for amount
if (!isset($_POST["amount"])) {
$amountErr = "You must select an amount";
$formErrors = true;
}
else {
$amount = $_POST["amount"];
$formErrors = false;
}
// for gender
if (!isset($_POST["gender"])) {
$genderErr = "You must select your gender";
$formErrors = true;
}
else {
$gender = $_POST["gender"];
$formErrors = false;
}
// for country
if (empty($_POST["country"]) || $_POST["country"] == "Country") {
$countryErr = "Please, select your country";
$formErrors = true;
}
else {
$country = $_POST["country"];
$formErrors = false;
}
// for category
if (empty($_POST["category"]) || $_POST["category"] == "Category") {
$categoryErr = "Please, select a category";
$formErrors = true;
} else {
$category = $_POST["category"];
$formErrors = false;
}
// for message
if (empty($_POST["message"]) || $_POST["message"] == $defaultMessage){
$messageErr = "Please type your prayer request";
$formErrors = true;
}else{
$message = $_POST["message"];
$formErrors = false;
}
if (empty($formErrors) ) {
//connect to database
require_once("../../includes/connect_to_db.php");
// set time zone to uk
$timezone = date_default_timezone_set("Europe/london");
//setting values
$Timestamp = date('Y-m-d h:i:s');
$fname = $_POST["fname"];
$lname = $_POST["lname"];
$email = $_POST["email"];
$phone = $_POST["phone"];
$gender = isset($_POST["gender"]) ? $_POST["gender"] : '';
$message = $_POST["message"];
$country = $_POST["country"];
$category = $_POST["category"];
//echo $gender . "value";
//var_dump(billingDate);
// var_dump($customer);
//Escape all string
$firstname = mysqli_real_escape_string($connection, $fname);
$lastname = mysqli_real_escape_string($connection, $lname);
$emailNew = mysqli_real_escape_string($connection, $email);
$phoneNew = mysqli_real_escape_string($connection, $phone);
$genderNew = mysqli_real_escape_string($connection, $gender);
$messageNew = mysqli_real_escape_string($connection, $message);
$countryNew = mysqli_real_escape_string($connection, $country);
$categoryNew = mysqli_real_escape_string($connection, $category);
//querying the database
$query = "INSERT into counselling ( ";
$query .= "Timestamp, FirstName, LastName, ";
$query .= "Email, PhoneNumber, Category, Country, Gender, Message";
$query .= ")";
$query .= "VALUES ('{$Timestamp}', '{$firstname}', '{$lastname}', ";
$query .= "'{$emailNew}', '{$phoneNew}', '{$categoryNew}', '{$countryNew}', '{$genderNew}', '{$messageNew}' ";
$query .= ")";
echo $query;
$result = mysqli_query($connection, $query) ;
//check for query error
if($result){
//query success redirect_to ("somepage.php");
//redirect_to("confirmation.php");
echo "Success";
} else {
die("Database query failed");
}
} // end of if
} // End of form submission conditional.
?>

Your need to refactor your code with proper logic.
<?php
$fname = $_POST["fname"];
$lname = $_POST["lname"];
$errors = array();
if(trim($fname) == ''){
$errors['fname'] = "First name is required";
}
if(trim($lname) == ''){
$errors['lname'] = "Last name is required";
}
if(count( $errors) > 0){
//form invalid
}
else{
//form is valid
}

Related

my form submits a bad entry even though it gets validated, how can I prevent this?

Using PHP, the validation on my form is correct and I even use a redirect header when the form is submitted correctly, this part works just fine, however, when the form is validated or showing errors a entry is submitted when it should not, is their anything I need to be added to my code base to fix this bug, take a look at my code below..
<?php
$e_first = ""; $e_last = ""; $e_email = ""; $success = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
require_once("config.php");
require_once("database.php");
require_once("controller.php");
$firstname = sanitize($_POST['firstname']);
$lastname = sanitize($_POST['lastname']);
$email = sanitize($_POST['email']);
$submit = sanitize($_POST['submit']);
if (empty($firstname)) {
$e_first = "First Name is required";
} else {
$firstname;
if (!preg_match("/^[a-zA-Z ]*$/", $firstname)) {
$e_first = "Only letters and white space allowed";
}
}
if (empty($lastname)) {
$e_last = "Last Name is required";
} else {
$lastname;
if (!preg_match("/^[a-zA-Z ]*$/", $lastname)) {
$e_last = "Only letters and white space allowed";
}
}
if (empty($email)) {
$e_email = "Email Address is required";
} else {
$email;
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$e_email = "Invalid Email Address";
}
}
$users = [
'firstname' => $firstname,
'lastname' => $lastname,
'email' => $email
];
$control = new Controller();
$control->addCustomer($users);
if (isset($submit)) {
switch (false) {
case !empty($firstname) || $firstname == $e_first :
$success = "";
break;
case !empty($lastname) || $lastname == $e_last :
$success = "";
break;
case !empty($email) || $email == $e_email :
$success = "";
break;
default :
$success = "Thank you $firstname $lastname";
header("Location: success.php");
break;
}
}
}
function sanitize($data) {
$data = htmlspecialchars($data);
$data = stripslashes($data);
$data = strip_tags($data);
$data = trim($data);
return $data;
}
?>
The bit where you add the user should be after you check for errors
default :
$control = new Controller();
$control->addCustomer($users);
$success = "Thank you $firstname $lastname";
header("Location: success.php");
break;

Prevent storing invalid information in sql database

I have made this form where users can input various information,Everything is fine i am checking for different errors also but the problems is if user inputs email with a invalid email format and when pressing sumbit button it gives error invalid email format which is fine but mydatabase stores the invalid email also,How to prevent storing some invalid information?? And i am new to programming.
Thanks in advance.
$nameErr = $adressErr = $emailErr = $passwordErr = $genderErr = "";
$name = $adress = $email = $password = $gender = "";
if(isset($_POST['sumbit'])){
if (empty($_POST["name"])){
$nameErr = "Name is required";
}else{
$name = $_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["adress"])){
$adressErr = "Adress is required";
}else{
$adress = $_POST["adress"];
}
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["password"])){
$passwordErr = "Password is required";
}else{
$password = $_POST["password"];
}
if(empty($_POST["gender"])){
$genderErr = "Gender is required";
}else{
$gender = $_POST["gender"];
}
}
$sql = "INSERT INTO users(name,adress,email,password,gender)VALUES(:name,:adress,:email,:password,:gender)";
$statement = $conn->prepare($sql);
$statement->bindParam(":name",$name);
$statement->bindParam(":adress",$adress);
$statement->bindParam(":email",$email);
$statement->bindParam(":password",$password);
$statement->bindParam(":gender",$gender);
$statement->execute();
?>
Create a Boolean on top
$hasError = false;
In case of all error, set Boolean true as $hasError = true;
Before sql query :
if($hasError){
// redirect to form page -- pass the ERROR in the url as get and then show the error on form page
}
else{
// execute query code
}
It's good have server side checks, you can add a lot of validation on client side too.
Client side checks
For email, you can use type='email' instead of type='text'. Similarly, you can have maxlength, required, etc. to avoid erroneous data.
You first checked all field validation one by one and then executed your insert query. That's why always creating a new rows into database in both cases inputs are valid or invalid.
you should put your insertion query in the block if only inputs are valid.
Try this -
<?php
$nameErr = $adressErr = $emailErr = $passwordErr = $genderErr = "";
$name = $adress = $email = $password = $gender = "";
$error = array();
if(isset($_POST['sumbit'])){
if (empty($_POST["name"])){
$error[] = "Name is required";
}else{
$name = $_POST["name"];
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$error[] = "Only letters and white space allowed";
}
}
if(empty($_POST["adress"])){
$error[] = "Adress is required";
}else{
$error[] = $_POST["adress"];
}
if(empty($_POST["email"])){
$error[] = "Email is required";
}else{
$email = $_POST["email"];
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error[] = "Invalid email format";
}
}
if(empty($_POST["password"])){
$error[] = "Password is required";
}else{
$password = $_POST["password"];
}
if(empty($_POST["gender"])){
$error[] = "Gender is required";
}else{
$gender = $_POST["gender"];
}
}
if(empty($error)){
$sql = "INSERT INTO users(name,adress,email,password,gender)VALUES(:name,:adress,:email,:password,:gender)";
$statement = $conn->prepare($sql);
$statement->bindParam(":name",$name);
$statement->bindParam(":adress",$adress);
$statement->bindParam(":email",$email);
$statement->bindParam(":password",$password);
$statement->bindParam(":gender",$gender);
$statement->execute();
}else{
foreach ($error as $key => $value) {
echo '<li>'.$value.'</li>';
}
}
?>

PHP MySQL Update not working when using variable in WHERE clause

I've checked dozens of threads on here and on other sites, and I cannot figure out why my code is not working. I am trying to use PHP to update MySQL using a variable to identify WHERE. The code I have works if I swap the variable for a number, and the variable works everywhere else in my script. It's just this one line that does not.
The line in question is:
$change = "UPDATE reg_info SET fname='$fname', lname='$lname', email='$email', explevel='$experience', addinfo='$additional', event='$regEvent' where id='$id'";
I've also tried the following:
$change = mysqli_query("UPDATE reg_info SET fname='$fname', lname='$lname', email='$email', explevel='$experience', addinfo='$additional', event='$regEvent' where id='$id'");
$change = "UPDATE reg_info SET fname='$fname', lname='$lname', email='$email', explevel='$experience', addinfo='$additional', event='$regEvent' where id=".$id;
$change = 'UPDATE reg_info SET fname="'.$fname.'", lname="'.$lname.'", email="'.$email.'", explevel="'.$experience.'", addinfo="'.$additional.'", event="'.$regEvent.'" where id='.$id;
From what I've seen on other threads, at least one of these should worked for me.
Can anyone point me in the right direction, please?
If it helps the entire string of PHP code is:
<?php
$fnameErr = $lnameErr = $emailErr = $experienceErr = $regEventErr = "";
$fname = $lname = $email = $experience = $regEvent = "";
$id = $_GET["id"];
$errors = "yes";
$servername = "localhost";
$username = "root";
$password = "5tTtFzaz6dIO";
$database = "project2db";
$conn = new mysqli($servername, $username, $password, $database);
$query = mysqli_query($conn, "SELECT * FROM reg_info where id=".$id);
$row = mysqli_fetch_array($query, MYSQLI_NUM);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fname"])) {
$fnameErr = "First name is required";
$errors = "yes";
} else {
$fname = test_input($_POST["fname"]);
if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
$fnameErr = "Only letters and white space allowed";
$errors = "yes";
}
else {
$errors = "no";
}
}
if (empty($_POST["lname"])) {
$lnameErr = "Last name is required";
$errors = "yes";
} else {
$lname = test_input($_POST["lname"]);
if (!preg_match("/^[a-zA-Z ]*$/",$lname)) {
$lnameErr = "Only letters and white space allowed";
$errors = "yes";
}
else {
$errors = "no";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
$errors = "yes";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email address";
$errors = "yes";
}
else {
$errors = "no";
}
}
if (empty($_POST["experience"])) {
$experienceErr = "Experience level is required";
$errors = "yes";
} else {
$experience = test_input($_POST["experience"]);
$errors = "no";
}
if (empty($_POST["additional"])) {
$regEvent = "";
} else {
$additional = test_input($_POST["additional"]);
}
if (empty($_POST["regEvent"])) {
$regEventErr = "Event is required";
$errors = "yes";
} else {
$regEvent = test_input($_POST["regEvent"]);
$errors = "no";
}
if($errors == "no") {
$change = 'UPDATE reg_info SET fname="'.$fname.'", lname="'.$lname.'", email="'.$email.'", explevel="'.$experience.'", addinfo="'.$additional.'", event="'.$regEvent.'" where id='.$id;
$result=$conn->query($change);
if ($result) {
echo '<script language="javascript">';
echo 'alert("New record created successfully.")';
echo '</script>';
header('Location: regtable.php');
} else {
echo '<script language="javascript">';
echo 'alert("Error. New record not created.")';
echo '</script>';
header('Location: regtable.php');
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
I figured out the issue! Whenever the form was submitted, the new POST data did not have anything assigned to the html id="id" that was passed into the PHP code to create the $id variable.
Since there was nothing in the form, $id was null, and thus the query did not update the database, even though the query and connection were completely valid.
Thanks to everyone who posted comments and advice, I really appreciate it.
Since the query in itself is valid, I can only guess that somehow the data is causing the issue. Try the following, which escapes every value that will be used in the query:
$fname = mysqli_real_escape_string( $conn, $fname );
$lname = mysqli_real_escape_string( $conn, $lname );
$email = mysqli_real_escape_string( $conn, $email );
$experience = mysqli_real_escape_string( $conn, $experience );
$additional = mysqli_real_escape_string( $conn, $additional );
$regEvent = mysqli_real_escape_string( $conn, $regEvent );
$id = mysqli_real_escape_string( $conn, $id );
$change = "UPDATE reg_info SET fname='$fname', lname='$lname', email='$email', explevel='$experience', addinfo='$additional', event='$regEvent' where id='$id'";

How to echo Empty Entry Prohibited Message generated from a query in php?

I have a form which when submitted, checks this query ->
if(isset($_POST['update']) && !empty($_POST['name']) && !empty($_POST['reg_name']))
I want to echo a message "Please fill up all the required fields." if the required fields are not filled up.
In short, it should highlight the field name which is not filled up.
The Full Code:
include ('database/abcd.php');
if ($con->connect_error)
{
die("Connection failed: " . $con->connect_error);
}
if(isset($_POST['update']))
{
$error = array();
if(empty($_POST['name']))
$error[] = 'Please fill name field';
if(empty($_POST['reg_name']))
$error[] = 'Pleae fill reg_name field';
if(count($error) < 1)
{
$name = $_POST['name'];
$reg_name = $_POST['reg_name'];
$established = $_POST['established'];
$industry = $_POST['industry'];
$about = $_POST['about'];
$website = $_POST['website'];
$mail = $_POST['mail'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$city = $_POST['city'];
$facebook = $_POST['facebook'];
$wiki = $_POST['wiki'];
$twitter = $_POST['twitter'];
$google = $_POST['google'];
$member_username = $_SESSION['username'];
$process="INSERT INTO notifications (member_username, process, icon, class) VALUES ('$_POST[member_username]','$_POST[process]','$_POST[icon]','$_POST[class]')";
if (!mysqli_query($con,$process))
{
die('Error: ' . mysqli_error($con));
}
$sql = "UPDATE `company_meta` SET `name` = '$name', reg_name = '$reg_name', wiki = '$wiki', established = '$established', industry = '$industry', about = '$about', website = '$website', mail = '$mail', phone = '$phone', address = '$address', city = '$city', facebook = '$facebook', twitter = '$twitter', google = '$google' WHERE `member_username` = '$member_username'";
if ($con->query($sql))
{
header('Location: edit.php');
}
}
else
{
$errors = implode(',' $error);
echo $errors;
}
$con->close();
}
I think what you are pass in name or reg_name is check first .may be name or reg_name can content white space so that it not showing message otherwise above code is working correctly..
if(isset($_POST['update'])) // This first check whether it is an update call
{
$error = array(); // Here we initialize an array so that we can put the messages in it.
if(empty($_POST['name'])) // If the name field is empty, push a message in $error array.
$error[] = 'Please fill name field';
if(empty($_POST['reg_name'])) // Same as above field
$error[] = 'Pleae fill reg_name field';
if(count($error) < 1) // Now this checks if the $error array has no value. If it has value it means that either or both of the above fields are empty and the else block will be executed.
{
// Submit your form
}
else
{
$errors = implode(',' $error);
echo $errors;
}
}
else
{
// Update not triggered.
}

PHP form order of functions

Okay, I tried once again, this time I removed the multiple php open/closing tags. So below is one big php chunk of code. If I fill out the form and send, the redirect works and I get the email - this all works great. The one last problem is the validation - I can submit empty fields and it redirects to the thankyou page - it doesn't warn users to fill out the fields...
So why now is the validation not working??? Thanks for your help guys.
<?php
// define variables and set to empty values
$fname = $lname = $email = $phone = $location = $size = $pvtype = $message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$company = test_input($_POST["company"]);
$fname = test_input($_POST["first-name"]);
$lname = test_input($_POST["last-name"]);
$email = test_input($_POST["email"]);
$phone = test_input($_POST["phone"]);
$address = test_input($_POST["address"]);
$city = test_input($_POST["city"]);
$provincestate = test_input($_POST["provincestate"]);
$country = test_input($_POST["country"]);
$location = test_input($_POST["location"]);
$size = test_input($_POST["size"]);
if(isset($_POST["type"])){ $type = $_POST['type'];}
$message = test_input ($_POST["message"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// define variables and set to empty values
$companyErr = $fnameErr = $lnameErr = $emailErr = $phoneErr = $addressErr = $cityErr = $provincestateErr = $countryErr = $locationErr = $sizeErr = $typeErr = $messageErr ="";
$company = $fname = $lname = $email = $phone = $address = $city = $provincestate = $country = $location = $size = $type ="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["company"])) {
$company = "";
} else {
$company = test_input($_POST["company"]);
}
if (empty($_POST["first-name"])) {
$fnameErr = "First name is required";
} else {
$fname = test_input($_POST["first-name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
$fnameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["last-name"])) {
$lnameErr = "Last name is required";
} else {
$lname = test_input($_POST["last-name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lname)) {
$lnameErr = "Only letters 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["phone"])) {
$phoneErr = "Phone number is required";
} else {
$phone = test_input($_POST["phone"]);
// check if phone number only contains 10 digits with no formatting
if (!preg_match("/^[0-9]{10}+$/",$phone)) {
$phoneErr = "Only enter a 10 digit number";
}
}
if (empty($_POST["address"])) {
$address = "";
} else {
$address = test_input($_POST["address"]);
}
if (empty($_POST["city"])) {
$city = "";
} else {
$city = test_input($_POST["city"]);
}
if (empty($_POST["provincestate"])) {
$provincestate = "";
} else {
$provincestate = test_input($_POST["provincestate"]);
}
if (empty($_POST["country"])) {
$country = "";
} else {
$country = test_input($_POST["country"]);
}
if (empty($_POST["location"])) {
$locationErr = "Location is required";
} else {
$location = test_input($_POST["location"]);
// check if location only contains letters
if (!preg_match("/^[a-zA-Z ]*$/",$location)) {
$locationErr = "Please enter a city";
}
}
if (empty($_POST["size"])) {
$sizeErr = "Please enter a number";
} else {
$size = test_input($_POST["size"]);
}
if (empty($_POST["type"])) {
$typeErr = "Please select 1";
} else {
$type = test_input($_POST["type"]);
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
}
$myemail = 'dgillison#sentinelsolar.com';//<-----Put Your email address here.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$to = $myemail;
$email_subject = "Inquiry from: $fname $lname";
$email_body = "You have received a new inquiry from:".
"\n
\n Name: $fname $lname \n Email: $email \n Phone Number: $phone
\n Address: $address \n City: $city \n Province/State: $provincestate \n Country: $country
\n I have a project in: $location \n The project type is: $type \n The estimated project size is: $size
\n Message: $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: thankyou.html');
exit();
}
?>
header() has to come before any output, so having it at the bottom will not work. Right now you don't really have an email 'function'. You can wrap that bottom piece of code into a sendEmail function. Then put the call to the function at the end of if ($_SERVER["REQUEST_METHOD"] == "POST") {.
You would have to pass all the variables in to the function. Or you could pass $_POST and do you variable cleaning in one function.
Move the email part up above the html, where it was redirecting automatically before. You need to add a check to see if there was a post request before sending the email and redirecting. Right after you set $myemail, there is an open bracket. Change this to:
if ($_SERVER["REQUEST_METHOD"] == "POST") {

Categories