Php Form - Error Checking - php

I have created a form online and when the user clicks submit I want the form to check for error (ie missing field). At the moment I have the form checking the fields one by one and as soon as it encounters a error it will exit without checking the rest of the fields. Is there any way I can combine all the if statements that check for errors into one.
Here is the code
//Code to check that the Student Name field is completed
if(empty($_POST['studentName']))
{
$studentNameError = "You did not enter the student name Wank";
//echo "<h3> $studentNameError </h3>";
exit();
}
//Code to check that the Tutor Name field is completed
if(empty($_POST['tutorName'] ))
{
echo "<h3>You did not select a tutor name. Please go back and select your name from the tutors list</h3>";
exit();
}
//Code to check that the Procedure field is completed
if(empty($_POST['procedure'] ))
{
echo "<h3>You did not select a procedure. Please go back and enter the name of the procedure which you undertook</h3>";
exit();
}
//Code to check that the Grade field is completed
if(empty($_POST['grade'] ))
{
echo "<h3>You did not select a grade. Please go back and select your grade from the drop down list</h3>";
exit();
}
//Code to check that the Student Reflection field is completed
if(empty($_POST['studentReflection'] ))
{
echo "<h3>The student did not enter any comments for this procedure. Student reflection is required for each procedure. Please go back and enter any comments</h3>";
exit();
}
//Code to check if the tick box is checked that the tutor comment is entered
if( !strlen($_POST['tutorComments']) && isset($_POST['alert'] ))
{
echo "<h3>You must enter a reason why you have clicked the alert box</h3>";
exit();
}

For example, you can make a boolean variable to mark, if there is an error, and exit if it's true + combine error messages into one
$error = false;
if(empty($_POST['studentName']))
{
$errorMessages[] = "You did not enter the student name Wank";
$error = true;
}
//Code to check that the Tutor Name field is completed
if(empty($_POST['tutorName'] ))
{
$errorMessages[] = "You did not select a tutor name. Please go back and select your name from the tutors list";
$error = true;
}
//Code to check that the Procedure field is completed
if(empty($_POST['procedure'] ))
{
$errorMessages[] = "You did not select a procedure. Please go back and enter the name of the procedure which you undertook";
$error = true;
}
//Code to check that the Grade field is completed
if(empty($_POST['grade'] ))
{
$errorMessages[] ="You did not select a grade. Please go back and select your grade from the drop down list";
$error = true;
}
//Code to check that the Student Reflection field is completed
if(empty($_POST['studentReflection'] ))
{
$errorMessages[] = "The student did not enter any comments for this procedure. Student reflection is required for each procedure. Please go back and enter any comments";
$error = true;
}
//Code to check if the tick box is checked that the tutor comment is entered
if( !strlen($_POST['tutorComments']) && isset($_POST['alert'] ))
{
$errorMessages[] = "You must enter a reason why you have clicked the alert box";
$error = true;
}
if($error)
{
echo("<h3>".implode('<br/>',$errorMessages)."</h3>");
exit();
}

There are many ways. How about something like this, from top of my head:
$textFieldsThatCannotBeEmpty = array(
'studentName' => 'You did not enter the student name Wank',
'tutorName' => 'You did not select a tutor name. Please go back and select your name from the tutors list',
'procedure' => 'You did not select a procedure. Please go back and enter the name of the procedure which you undertook',
'grade' => 'You did not select a grade. Please go back and select your grade from the drop down list',
'studentReflection' => 'The student did not enter any comments for this procedure. Student reflection is required for each procedure. Please go back and enter any comments'
);
$errors = array();
// check text input fields
foreach($textFieldsThatCannotBeEmpty as $name => $errorMessage){
if(empty($_POST[$name])){
$errors[] = $errorMessage;
}
}
// checkbox
if(!strlen($_POST['tutorComments']) && isset($_POST['alert'])){
$errors[] = 'You must enter a reason why you have clicked the alert box';
}
if(count($errors) > 0){
// form is invalid, print errors
echo '<div class="errors">';
foreach($errors as $e){
echo '<h3>',htmlentities($e),'</h3>';
}
echo '</div>';
}else{
// form is valid, let's go and do something with the submitted data
}

Put all your error messages into an array, and loop through the $_POST. If the input field is empty, then echo the error message:
<?php
$errorMsgs = array(
'studentName' => 'You did not enter a student name',
...
);
$errors = '';
foreach($_POST as $field)
{
if(empty($field))
{
$errors .= $errorMsgs[$field] . '<br/>';
}
}
if(strlen($errors))
{
echo $errors;
exit();
}

This can be done like that (one of the many ways -- really depends on your exact requirements for validation):
<?php
$messages = array();
$errors = 0;
if (empty($_POST['studentName']))
{
$messages['studentName'] = "You did not enter the student name Wank";
$errors++;
}
if (empty($_POST['tutorName']))
{
$messages['tutorName'] = "<h3>You did not select a tutor name. Please go back and select your name from the tutors list</h3>";
$errors++;
}
if ($errors) {
// we have some invalid data in one of the fields
// display error messages (some feedback to user)
foreach ($messages as $v) {
echo $v, "\n";
}
exit();
}
// nope, we are fine
// do whatever else is required

Make a variable named $status for example and and initialize it to 0, at each test assign to it 1 if there is an error, at the end check whether if it is equal to one, exit the script otherwise continue the execution. Or better make an array and for each test assign 0 or 1, depend in the test(the field is not empty assign one else zero) and later you can echo an error message to user indicating the missing fields.

Related

How to change php code to show errors under each input box

I have the following code :
if(isset($_POST['submit'])){
if (! isset($_POST['firstname'])) {
$error[] = "Please fill out all fields";
}
if (! isset($_POST['surname'])) {
$error[] = "Please fill out all fields";
}
........
with validation:
if (strlen($_POST['firstname']) < 2){
$error[] = 'First name cannot be empty';
}
if (strlen($_POST['surname']) < 2){
$error[] = 'Please provide your surname';
}
......
More checks are made with the database....
This checks for errors and displays them in one go:
if(isset($error)){
foreach($error as $error){
echo '<p class="error-login">'.$error.'</p>';
}
}
While this is working fine, I would like errors to be shown under each input box where there is an error happening.
I don't want to change the entire code, just want to make the necessary changes to this one, which I am incapable of doing myself.
Is putting them in array the only approach here or is there a simpler way ?
Thanks.
The approach is - add errors to $error under a certain key, I presume - name of the input field:
if(isset($_POST['submit'])){
// I use key `all` for errors that don't belong to any field
if (! isset($_POST['firstname'])) {
$error['all'] = "Please fill out all fields";
}
if (! isset($_POST['surname'])) {
$error['all'] = "Please fill out all fields";
}
if (strlen($_POST['surname']) < 2){
$error['surname'] = 'Please provide your surname';
}
In your html markup:
// general errors, not related to inputs
if(isset($error['all'])){
foreach($error['all'] as $err){
echo '<p class="error-login">'.$err.'</p>';
}
}
<input type="text" name="surname" />
<?php
if(isset($error['surname'])){
foreach($error['surname'] as $err){
echo '<p class="error-login">'.$err.'</p>';
}
}

My code is showing no errmsg but is not inserting any data into database

So I am trying to make a simple e-commerce site. Once I submit the form (btn-submit), I am not able to insert any data to my database. Only the address and contact number verification works.
Here is my code:
if ( isset($_POST['btn-submit']) ) {
// clean user inputs
$oadd = trim($_POST['oadd']);
$oadd = strip_tags($oadd);
$oadd = htmlspecialchars($oadd);
$contact = trim($_POST['contact']);
$contact = strip_tags($contact);
$contact = htmlspecialchars($contact);
// address validation
if (empty($oadd)) {
$error = true;
$oaddError = "Please enter a valid address.";
} else if (strlen($oadd) < 5) {
$error = true;
$oaddError = "Please enter a valid address.";
}
// contact number validation
if (empty($contact)) {
$error = true;
$contactError = "Please enter your contact number.";
} else if (strlen($contact) < 7) {
$error = true;
$contactError = "Contact number must have atleast 7 digits.";
} else if (!preg_match("/^[0-9 ]+$/",$lname)) {
$error = true;
$lnameError = "Please enter a valid contact number.";
}
// if there's no error, continue to place order
if( !$error ) {
$query = 'INSERT INTO cust_order(Order_Date, Order_Status, Order_Total , Address, Contact_No) VALUES (CURDATE(), "in process" , (SELECT SUM(p.Product_Price) FROM cart c, product p WHERE c.Prod_ID = p.Product_ID and c. User_ID = "'.$userRow['User_ID'].'"),"'.$oadd.'","'. $contact.'")';
$res = mysql_query($query);
if ($res) {
$errTyp = "success";
$errMSG = "Your order has been placed. To view the details, go to your order history";
unset($oadd);
unset($contact);
} else {
$errTyp = "danger";
$errMSG = "Something went wrong. Please try again later.";
}
}
}
What could possibly be wrong with my code? I did similar queries in the other pages but this is the only one not working. Any help would be greatly appreciated! Thanks in advance!
Try to understand the code flow:
if( !$error ) {
// This will only works when **$error is false and the not of false is true**, otherwise this block does not execute
}
So this code works only when there is no validation error occurs in your code and $error contains false
//$userRow is not define any where...
//to check error occur or not :
echo $error;
if(!$error)
{
echo "IN IF";
//also go with die..
$res = mysql_query($query) or die();
}
else
{
echo "IN ELSE";
}

Creating a registration page in PHP

Hi guys so im creating this registration page for my website in php..This is the PHP script
# Script 9.5 - register.php #2
// This script performs an INSERT query to add a record to the users table.
$page_title = 'Register';
include ('includes/header.html');
// Check for form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array(); // Initialize an error array.
// Check for a name:
if (empty($_POST['name'])) {
$errors[] = 'You forgot to enter your name.';
} else {
$n = mysqli_real_escape_string($dbh, trim($_POST['name']));
}
// Check for an email:
if (empty($_POST['email'])) {
$errors[] = 'You forgot to enter your email.';
} else {
$e = mysqli_real_escape_string($dbh, trim($_POST['email']));
}
// Check for a password and match against the confirmed password:
if (!empty($_POST['pass1'])) {
if ($_POST['pass1'] != $_POST['pass2']) {
$errors[] = 'Your password did not match the confirmed password.';
} else {
$p = mysqli_real_escape_string($dbh, trim($_POST['pass1']));
}
} else {
$errors[] = 'You forgot to enter your password.';
}
// Check for contact number:
if (empty($_POST['contact_no'])) {
$errors[] = 'You forgot to enter your contact no.';
} else {
$cn = mysqli_real_escape_string($dbh, trim($_POST['contact_no']));
}
if (empty($errors)) { // If everything's OK.
require 'connect_db.php';
$conn= mysqli_connect('*****' , '*****', '*****' , '*****' ,****);
// Make the query:
$q = ("INSERT INTO register_user(name, email, pass, contact_no) VALUES ('$n', '$e','$p','$cn')");
$r = #mysqli_query ($dbh, $q);// Run the query.
if ($r) { // If it ran OK.
// Print a message:
echo '<h1>Thank you!</h1>
<p>You are now registered. </p>
<p>Login </p>';
} else { // If it did not run OK.
// Public message:
echo '<h1>System Error</h1>
<p class="error">You could not be registered due to a system error. We apologize for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbh) . '<br/><br/> Query: ' . $q . '</p>';
} // End of if ($r) IF.
mysqli_close($dbh); // Close the database connection.
// Include the footer and quit the script:
include ('includes/footer.html');
exit();
} else { // Report the errors.
echo '<h1>Error!</h1>
<p class="error">The following error(s) occurred:<br>';
foreach ($errors as $msg) { // Print each error.
echo " - $msg<br>";
}
echo 'Please try again.</p>';
} // End of if (empty($errors)) IF.
mysqli_close($dbh); // Close the database connection.
But the thing is once i register this is the output:
System Error
You could not be registered due to a system error. We apologize for any inconvenience.
Query: INSERT INTO register_user(name, email, pass, contact_no) VALUES ('', '','','')
so im kindly would glad for any assistance
You're calling mysqli_real_escape_string() BEFORE you establish your DB connection. This is not permitted. You MUST have a connection before doing the escape operations.
That means every single one of your form fields is going to be a boolean FALSE value, which signifies failure.
Your code should be structured
1. connect to db
2. process form inputs
3. if form inputs ok, insert into db
You've got #1 and #2 reversed.

PHP Basics - Echo messages in a redirected page

I have a website, which you press a button and a popup DIV loads up.
On this DIV is a JQuery Validator form which submits to a separate PHP file.
The PHP logins to a database through MySQLi and adds a user. Whilst it does it, at each stage it does an echo message (the idea is that I know what its doing).
This leaves me with a white screen with several lines of information. Its fantastically useful but very ugly from the nice popup div registration.
Is there any way, at the end of the PHP it can redirect to another page assuming there was a blank div in it where the echo information can go, and I can jazz the remaining page up with HTML5 and CSS.
If so how do I get the echo messages into this div?
Thanks
Please see the snippet (which is working) below - but go easy on me as its only been a couple of weeks of learning.
function webmailSignUp($db_connection,$db_con_table) //The function for the website REGISTER FORM
{
$webmailFullName = $_POST['webmailFullName'];
$webmailUserName = $_POST['webmailUserName'];
$webmailExEmail = $_POST['webmailExEmail'];
$webmailPhone = $_POST['webmailPhone'];
$webmailDOB = $_POST['webmailDOB'];
//Check that the fields are not empty
if (checkBlankFieldsError($webmailFullName,$webmailUserName,$webmailExEmail,$webmailPhone,$webmailDOB) == false)
{
echo "There are no empty Form Input Fields<br>";
//Connecting to MySQL
if (mysqli_connect_errno($db_connection))
{
echo "Failed to connect to MySQL database:" . mysqli_connect_error();
echo "<br>";
}
else
{
echo "Connected to database<br>";
//Check that there is no existing name in the table
if (checkInField($webmailUserName,$db_connection,$db_con_table,"userName") == false)
{
//Check DOB Field
$dob = $webmailDOB; //or use for non-iso: convertDate($webmailDOB);
echo "DOB is: $dob<br>";
//Binding and Query to prevent SQL injection
$query = "INSERT INTO $db_con_table(userFullName,userName,userExEmail,userPhone,userDOB) VALUES(?,?,?,?,?)";
$requery = $db_connection->prepare($query);
$requery->bind_param("sssss",$webmailFullName,$webmailUserName,$webmailExEmail,$webmailPhone,$dob);
if ($requery->execute())
{
echo "$webmailUserName has been added to the Webmail Database<br>";
}
else
{
echo "bind failed on $webmailUserName <br>";
}
//Close Database
$db_connection->close();
echo "Database is Closed.<br>";
}
else{echo "There is already a user registered with this username. Please try a different one.<br>";}
}
}
else
{
echo "There is 1 or more empty input fields. Please try again.<br>";
}
}
function checkInField($value,$db_connection,$db_con_table, $db_field) // Checks a value is not within a database field
{
$query = "SELECT $db_field FROM $db_con_table WHERE $db_field='$value'";
$result = $db_connection->query($query) or die($mysqli->error());
// GOING THROUGH THE DATA
if($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
echo "User $value found: '$row[$db_field]' in the table $db_con_table column $db_field<br>";
return true;
}
}
else
{
echo "User $value has not been found in the table $db_con_table column $db_field<br>";
return false;
}
}
function checkBlankFieldsError($field1,$field2,$field3,$field4,$field5) //Checks if form fields are blank
{
$fields = array($field1,$field2,$field3,$field4,$field5);
$error = false;
foreach($fields AS $fieldname) //Loop trough each fieldname in the fields array
{
if(empty($fieldname))
{
$error = true;
}
else
{
}
}
return $error;
}
function convertDate($aString) //Converts a String to a Date in Y-M-D format
{
$date2 = DateTime::createFromFormat('m/d/Y', $aString);
return $date2->format('Y-m-d');
}
//Main Code Sequence on form buttons
if(isset($_POST['webmailRegisterSubmit']))
{
webmailSignUp($mysqli_db,$db_table);
echo "End of Registration.<br>";
}
if(isset($_POST['webamilForgottenPWSubmit']))
{
webmailForgottenPassword();
echo "End of Password Reset Request.<br>";
}
If you really want a redirection, you will have to store your messages somewhere. I suggest you to save them in the user session. The workflow would be :
user do action (save form / get page : anything)
server treat the request and store a new "message" in a specific array in the user session (standard php $_SESSION) depending on the situation (error message ? success message ?). At this point you should store the message and its level (INFO/WARNING/ERROR/SUCCESS/etc)
server do a rediction (if needed)
create a method which :
retrieve all store message and delete them directly cause you want to display them only once
display them on your DIV
you're done
The good thing with this worklow is that it will work even without a redirection as you separate clearly messages addition/storing and display.
Hope this helps

Inserting PHP Session Variables into MySQL Database

I am having issues with my PHP code. I am trying to insert data into a mysql database using two session variables that I will need at a later time in the form. However whenever I submit the form I am returned with a "Unknown column in 'field list'" error.
The code is lengthy but you will likely need all of it to understand the issue.
<?php
session_start();
// Check for hazards and put them in an array if there is one selected
if($_SERVER['REQUEST_METHOD'] == 'POST') {
require ('../mysqli_connect.php'); //connect to the db
//Check for offender first name
if (empty($_POST['pris_firstname'])) {
$errors[] = 'You forgot to enter offender first name.';
} else {
$prisf=$_POST['pris_firstname'];
}
//Check for offender last name
if (empty($_POST['pris_lastname'])) {
$errors[] = 'You forgot to enter offender last name.';
} else {
$prisl=$_POST['pris_lastname'];
}
//Check for offender date of birth
$dob = ($_POST['pris_dateofbirth']);
//Check for offender phone number
if (empty($_POST['pris_phonenum'])) {
$errors[] = 'You forgot to enter offender Phone Number.';
} else {
$prisphone=trim($_POST['pris_phonenum']);
}
//Check for offender address
if (empty($_POST['pris_address'])) {
$errors[] = 'You forgot to enter offender Address.';
} else {
//$prisaddress=trim($_POST['pris_address']);
foreach($_POST["pris_address"] as $value) {
$prisaddress .= $value . '\n';
}
}
//Check for offender next of kin first name
if (empty($_POST['pris_kinfirstname'])) {
$errors[] = 'You forgot to enter next of kin first name.';
} else {
$kinfirst=trim($_POST['pris_kinfirstname']);
}
//Check for offender next of kin last name
if (empty($_POST['pris_kinlastname'])) {
$errors[] = 'You forgot to enter next of kin last name.';
} else {
$kinlast=trim($_POST['pris_kinlastname']);
}
//Check for offender next of kin phone number
if (empty($_POST['pris_kinphone'])) {
$errors[] = 'You forgot to enter next of kin area code.';
} else {
$kinphone=trim($_POST['pris_kinphone']);
}
if (empty($_POST['pris_kinrelation'])) {
$errors[] = 'You forgot to enter next of kin relation.';
} else {
$kinrelation=trim($_POST['pris_kinrelation']);
}
//Check for offender next of kin address
if (empty($_POST['pris_kinaddress'])) {
$errors[] = 'You forgot to enter next of kin street address.';
} else {
foreach($_POST["pris_kinaddress"] as $value2) {
$kinaddress .= $value2 . '\n';
}
}
if (empty($errors)) { //if everyhing is ok
$q = "INSERT INTO prisoner_profile (pris_status,
pris_firstname,
pris_lastname,
pris_dateofbirth,
pris_phonenum,
pris_address,
pris_kinfirstname,
pris_kinlastname,
pris_kinphone,
pris_kinaddress,
pris_kinrelation
) VALUES (
'$status',
".$_SESSION['pris_firstname'].", ".$_SESSION['pris_lastname'].",
'$dob',
'$prisphone',
'$prisaddress',
'$kinfirst',
'$kinlast',
'$kinphone',
'$kinaddress',
'$kinrelation'
)";
$r = #mysqli_query ($dbc, $q); //Run the query.
Hope someone can help!
The error is pretty much self-explanatory, it means that you have got a column name wrong in your database. I recomend you echo out the error for your query just for this case as:
$r = mysqli_query ($dbc, $q) or die (mysqli_error());
One of the columns that are listed in your INSERT statement does not actually exist in the prisoner_profile. Check your table schema.
The one obvious issue I can see here is that you haven't handled the escape characters in your query, and you have used a few \n characters in your code.
Use mysqli_real_escape_string to handle that when inputting the data to the database.
Something like
$q = mysqli_real_escape_string($q);

Categories