Multiple IF statements in simple form validation - php

I am a newbie and trying to implement a simple validation script after reading up, but I can't see how I can have multiple Ifs that will only do an sql insert if all required fields are met. Rather than having the multiple else statements, what is a syntax approach for having all the form validation Ifs together and if one of them fails, then the correct error is shown and the sql is not execute?
if(isset($_POST ['submit'])){
$user_ID = get_current_user_id();
$catErr = $ratingErr = $titleErr = $textErr = "";
if (empty($_POST["category"])) {
$catErr = "Category is required";
} else {
//DO THE INSERT BELOW!
}
if (empty($_POST["rating"])) {
$ratingErr = "Rating is required";
} else {
//DO THE INSERT BELOW!
}
if (empty($_POST["post_name"])) {
$postErr = "Title is required";
} else {
//DO THE INSERT BELOW!
}
if (empty($_POST["text"])) {
$textErr = "Text is required";
} else {
//DO THE INSERT BELOW!
}
//PDO query begins here...
$sql = "INSERT INTO forum(ID,
category,
rating,
post_name,
text

Use one variable for all the error messages and concatenate to it in the branches, so in the end if that variable is still empty string you won't do the insert. (And you don't need any of the empty else blocks that contain nothing but a comment.)
$err = "";
if (empty($_POST["category"])) {
$err .= "<br/>Category is required";
}
if (empty($_POST["rating"])) {
$err .= "<br/>Rating is required";
}
if (empty($_POST["post_name"])) {
$err .= "<br/>Title is required";
}
if (empty($_POST["text"])) {
$err .= "<br/>Text is required";
}
//PDO query begins here...
if($err=='')
{
$sql = "INSERT INTO forum(ID,
category,
rating,
...";
...
}

There are many solutions to your problem. Here are 3 methods of solving your issue.
You could combine all of your if statements like so:
if (empty($_POST['rating']) || empty($_POST'rating']) || ... ) { ... }
and separate them by double pipes.
You could also check the entire array:
if (empty($_POST)) $error = "There was an error!";
You could set a universal error variable and then output it.
A third solution could keep your current syntax but cut down on the amount of lines. You could save lines by doing without brackets. You can create an array and push your errors to the array.
Note: You can use empty() or isset().
// create an array to push errors to
$errors_array = array();
// if a particular field is empty then push the relevant error to the array
if(!isset($_POST['category'])) array_push($errors_array, "Category is required");
if(!isset($_POST['rating'])) array_push($errors_array, "Rating is required");
...
Once you have an array full of errors you can check for them like so:
// if the array is not empty (then there are errors! don't insert!)
if (count($errors_array) > 0) {
// loop through and echo out the errors to the page
for ($i = 0; $i < count($errors_array); $i++) {
echo $errors_array[i];
}
} else {
// success! run your query!
}

You should use javascript to validate the page before it is even processed into a post. This script will run client-side when they hit submit and catch errors before they even leave the page.
Here's a tutorial on how to do something like that: tutorial
Each field can have its own validation parameters and methods, and it will also make the page's code look a lot nicer.

I got it to go with this approach after showdev got me thinking that way. It's not very elegant perhaps, but does the trick, although all the user is taken to a blank page if there are errors and it simple says: Missing category (or whatever). Wondering if I can echo a link or something back to the page with the form from there so the user has an option like "go back and resubmit". Otherwise I will have to handle and display the errors alongside the form which will require a different approach altogether...
if(isset($_POST ['submit'])){
$errors = false;
if(empty($_POST['category'])) {
echo 'Missing category.<br>';
$errors = true;
}
if(empty($_POST['rating'])) {
echo 'Missing rating.<br>';
$errors = true;
}
if(empty($_POST['post_name'])) {
echo 'Missing title.<br>';
$errors = true;
}
if(empty($_POST['text'])) {
echo 'Missing text.<br>';
$errors = true;
}
if($errors) {
exit;
}
// THEN ADD CODE HERE. But how display form again if user makes errors and sees nothing but error message on page if they miss something (which is how it works now)

Generally, if you find yourself repeatedly writing very similar statements, using some sort of loop is probably a better way to go about it. I think what you said about "handling and displaying the errors alongside the form" is really what you need to do if you want the process to be user-friendly. If you put your validation script at the top of the file that has your form in it, then you can just have the form submit to itself (action=""). If the submission is successful, you can redirect the user elsewhere, and if not, they will see the form again, with error messages in useful places.
if (isset($_POST['submit'])) {
// define your required fields and create an array to hold errors
$required = array('category', 'rating', 'post_name', 'text');
$errors = array();
// loop over the required fields array and verify their non-emptiness
foreach ($required as $field) {
// Use empty rather than isset here. isset only checks that the
// variable exists and is not null, so blank entries can pass.
if (empty($_POST[$field])) {
$errors[$field] = "$field is required";
}
}
if (empty($errors)) {
// insert the record; redirect to a success page (or wherever)
}
}
// Display the form, showing errors from the $errors array next to the
// corresponding inputs

Related

Setting General Messages Using Flash Message

I have a simple register form, my form validates but will not show error messages or validation messages
This is my form function
function validate_new_user()
{
$errors = [];
if (isset($_POST['register'])) {
$email = $_POST['email'];
$name = str_replace(" ", "", $_POST['username']);
$password = $_POST['password'];
if (empty($email)) {
$errors[] = "Email Address is required";
}
if (empty($name)) {
$errors[] = "Username is required";
}
if (strlen($password) < 5) {
$errors[] = "Password must be at least 6 characters long";
}
if (!empty($errors)) {
set_message($errors[0], WARNING);
} else if (create_new_user($email, $name, $password)) {
set_message('Please check your email for user Information.', SUCCESS);
redirect_to_url("/user/login");
}
}
}
I call my validation function in my form page
<?php validate_new_user(); ?>
so if there is an error it should set message but don't.
now if it successfully it redirects to login and sets a flash message also and I call it with
<?php display_message(); ?>
That don't display a message either
Flash message code
define('SUCCESS', 'success');
define('INFO', 'info');
define('WARNING', 'warning');
function set_message($message, $type = 'success')
{
if (!empty($_SESSION['flash_notifications'])) {
$_SESSION['flash_notifications'] = [];
}
$_SESSION['flash_notifications'][] =
$message = [
'<div class="alert . $type .">$message</div>'
];
}
function display_message()
{
if (isset($_SESSION['flash_notifications'])){
return $_SESSION['flash_notifications'];
}
}
my goal is to use one set message for all notifications with styles but I cannot get none of the messages to display
I’ll assume you’re calling session_start() at the beginning of the script.
Your usage of functions makes the problem much easier to diagnose! Sometimes, though, it helps to have a different set of eyes look at it.
Your function set_message() has a couple of errors:
The initialization of $_SESSION['flash_notifications'] should occur if it is empty, but instead you are initializing if it is not empty. Hence nothing can be added
Malformed assignment. When you are building the message array to save in $_SESSION, there is no need to reassign $message. Also, usage of single quotes does not interpret variables within the quotes, so the html snippet is not what you expect.
Corrected function:
function set_message($message, $type = 'success')
{
if (empty($_SESSION['flash_notifications'])) {
$_SESSION['flash_notifications'] = [];
}
$_SESSION['flash_notifications'][] = '<div class="alert '. $type .'">'.$message.'</div>';
}
Note, it might be more understandable to write it this way:
$_SESSION['flash_notifications'][] = <<<FLASH
<div class="alert $type'">$message</div>
FLASH;
Your function display_message() is almost correct as is, except you’re returning an array, not a string. If you’re going to print it, it must be converted into a string:
function display_message()
{
if (isset($_SESSION['flash_notifications'])){
return join('',$_SESSION['flash_notifications']);
}
}
Then when you call it in your html, use the short print tag instead of the regular <?php tag:
<!— somewhere in your view (html output) —>
<?= display_message() ?>
<!— continue html —>

Processing Contact Form

I am adding a contact page to my website, but having issues with the comment text box. When the user enters invalid information into the name and email text field, the website redirects the user back to the contact page to fill out the correct information. However, I want the comment box to be optional for the user. For example, the user will enter their name and email, but doesn't have any comments. The code should then process the information. Currently, my code will redirect the user back to the contact page because the user did not enter any information into the comment box. Any suggestions on how to fix this error?
Thanks!
if (empty($_REQUEST['comment'])) {
$error = TRUE;
} else {
$comment = $_REQUEST['comment'];
$form['comment'] = $comment;
if (!preg_match("/^.{0,50}$/", $comment)) {
$error = TRUE;
$messages['comment'] = "<p class='errorMessage'> You have entered invalid information.</p>";
} else {
$_SESSION['comment'] = $comment;
}
}
If you want to allow the content box to be empty, just let an empty value be an acceptable value. This means only running your validation against that field if there is a value present. This means removing your if/else statement since empty($_REQUEST['comment']) is no longer a valid check.
if (!empty($comment) && !preg_match("/^.{0,50}$/", $comment)) {
I just added !empty($comment) && to your check which basically says, "if there is a value go ahead and validate it".
One thing you should also do if you use this code is trim whitespace from your comment box values. Otherwise a user could type a space character and that would not be considered empty:
$comment = trim($_REQUEST['comment']);
Final code:
$comment = trim($_REQUEST['comment']);
$form['comment'] = $comment; // I am assuming this is used elsewhere
if (!empty($comment) && !preg_match("/^.{0,50}$/", $comment)) {
$error = TRUE;
$messages['comment'] = "<p class='errorMessage'> You have entered invalid information.</p>";
} else {
$_SESSION['comment'] = $comment;
}

Global error message in php

I have a problem with the understanding of variable scopes.
I've got a huge .php file with many $_POST validations (I know that isn't not good practise). Anyways I want a little html-part above all the code which outputs an error message. This message I want to change in every $_POST validation function.
Example:
if($ERR) {
echo '<div class="error-message">'.$ERR.'</div>';
}
Now my functions are following in the same file.
if(isset($_POST['test']) {
$ERR = 'Error!';
}
if(isset($_POST['test2'] {
$ERR = 'Error 2!';
}
But that doesn't work. I think there's a huge missunderstanding and i'm ashamed.
Can you help me?
I didnt catch your question but maybe this is your answer:
<body>
<p id="error_message">
<?php if(isset($ERR)){echo $ERR;} ?>
</p>
</body>
and I suggest you to learn how to work with sessions.
and you should know that $_Post will be empty on each refresh or F5
You can do put the errors in array make them dynamic.
<?php
$error = array();
if (!isset($_POST["test"]) || empty($_POST["test"])) {
$error['test'] = "test Field is required";
} else if (!isset($_POST["test1"]) || empty($_POST["test1"])) {
$error['test1'] = "test Field is required";
}else{
//do something else
}
?>
You can also use switch statement instead of elseif which is neater.

Break Parent IF (Conditional)

How can i break parent if in PHP?
example this code:
if(true){ // This is parent conditional
if(true) { // This is child conditional
break parent conditinal
}
}
afterBreakDoMe();
From code above. I want when child conditional is true. Then it break parent conditional (exit from that conditional) and continue the rest of the code (afterBreakDoMe()).
Update - Real code
$errorMessage = '';
if(isset($_POST) && count($_POST)) { // Detect some user input
// validation
$countryName = trim($_POST['countryName']);
if($countryName == ''){ // validation user input, if false. exit from parent if and continue show html input (refer to $Render->output())
$errorMessage = 'Name must not be empty!';
}
header('Location: '.$baseUrl.'&page=tableShipping');
}
$Render->setTitle('Create New Country');
$form = $Render->parser('createCountry', array(
'errorMessage' => $errorMessage,
));
$Render->addContent($form);
$Render->output();
You cannot do that (except using goto, which is taboo), and should not do that. Swapping functionality for simplicity is a bad idea.
Based on your "real" code, your program flow doesn't make sense.
if($countryName == ''){ // validation user input, if false. exit from parent if and continue show html input (refer to $Render->output())
So, if it's true, you're going to set $errorMessage, then exit, leave the page, and never use it again? Why? You might as well just forget the error message, call the header(), then call exit;.
I've created the following code based on what I think you want to happen, and commented it as an explanation:
$errorMessage = '';
if(isset($_POST) && count($_POST)) { // Detect some user input
// validation
$countryName = trim($_POST['countryName']);
if($countryName == ''){ // validation user input, if false. exit from parent if and continue show html input (refer to $Render->output())
$errorMessage = 'Name must not be empty!';
} else {
// If there is no error, continue forward.
header('Location: '.$baseUrl.'&page=tableShipping');
exit; // Leave the page execution since you've applied a header.
}
}
// This will only execute if there is an error, since we left the page otherwise.
$Render->setTitle('Create New Country');
$form = $Render->parser('createCountry', array(
'errorMessage' => $errorMessage,
));
$Render->addContent($form);
$Render->output();
All in all, consider the flow of your program in order to determine what happens next, not what to skip.
You could use a variable and an extra if-statement:
$errorMessage = '';
$emptyCountry = false;
if(isset($_POST) && count($_POST)) { // Detect some user input
// validation
$emptyCountry = trim($_POST['countryName']) == '';
if($emptyCountry){ // validation user input, if false.
$errorMessage = 'Name must not be empty!';
}
header('Location: '.$baseUrl.'&page=tableShipping');
}
if (!emptyCountry) {
$Render->setTitle('Create New Country');
$form = $Render->parser('createCountry', array(
'errorMessage' => $errorMessage,
));
$Render->addContent($form);
}
$Render->output();
Simple
if (true) {
if (true) {
// Do stuff
// It will then break automaticly
// but if the condition here is false you got the else ;)
} else {
}
}
Use goto. This is used for jumping in code
Now that I can read the real code sample I think what you need to do is simple put all the conditionals together in a single. Using goto will get the job done but can easily make you code hard to read and maintain. Perhaps its time to rethink the program flow.
Anyway, what I am saying is something like this:
if(!empty($_POST) && isset($_POST['countryName']) && (trim($_POST['countryName']) == '')){
$errorMessage = 'Name must not be empty!';
}
...
$errorMessage = '';
do {
if(isset($_POST) && count($_POST)) { // Detect some user input
// validation
$countryName = trim($_POST['countryName']);
if($countryName == ''){ // validation user input, if false. exit from parent if and continue show html input (refer to $Render->output())
$errorMessage = 'Name must not be empty!';
break;
}
header('Location: '.$baseUrl.'&page=tableShipping');
}
while(false);// only for break

If else block in PHP

I don't know where I am going wrong in else if logic...
I want to validate this signup script in 3 steps:
1st: check if any field is empty, in which case include errorreg.php and register.php.
2nd: If email already exists include register.php.
3rd: If all goes well insert data to the database.
<?php
$address =$_POST["add"];
$password =$_POST["pw"];
$firstname =$_POST["fname"];
$lastname =$_POST["lname"];
$email =$_POST["email"];
$contact =$_POST["cno"];
$con=mysql_connect("localhost","root","");
mysql_select_db("bookstore");
$q2=mysql_query("select * from customer where email='$email'");
$b=mysql_fetch_row($q2);
$em=$b[0];
if($password != $_POST['pwr'] || !$_POST['email'] || !$_POST["cno"] || !$_POST["fname"] || !$_POST["lname"] || !$_POST["add"])
{
include 'errorreg.php';
include 'register.php';
}
else if($em==$email)
{
echo 'email already present try another';
include 'register.php';
}
else
{
$con=mysql_connect("localhost","root","");
mysql_select_db("bookstore");
$q1=mysql_query("insert into customer values('$email','$password','$firstname','$lastname','$address',$contact)");
echo 'query completed';
$q2=mysql_query("select * from customer where email='$email'");
$a=mysql_fetch_row($q2);
print "<table border =2px solid red> <tr><th>id </th></tr>";
print "<td>$a[0]</td>";
print "</table>";
include 'sucessreg.php';
echo " <a href='newhome.php'>goto homepage</a>";
}
?>
There's a lot to correct here, but to your specific concern, that the "loop" doesn't go on to the second and third "steps", that's because you're thinking about this wrong. In an if/else if/else code block, only one of the blocks is executed at a time, the others are not. For instance, if a user submitted a number, we could tell them it was even or odd with the following:
if($_GET['number'] % 2 == 0){
echo "That's even!";
} else {
echo "That's odd!";
}
You are attempting to do one check, then another, then a third. In this case, you want to nest your conditionals (if statements) rather than have them come one after another, like so:
if(/* first, basic sanity check*/) {
if(/* second, more complex check */) {
if(/* final check */) {
// Database update
} else {
// Failed final check
}
} else {
// Failed second check
}
} else {
// Failed basic check
}
Some other comments on your code:
Pay attention to formatting - laying out your code in consistent and visually clear patterns will help make it easier to see when you make a mistake.
Use isset($_POST['variable']) before using $_POST['variable'], otherwise you'll get errors. One idea is to use lines like: $address = isset($_POST['address']) ? $_POST["add"] : ''; - if you don't know that notation, it lets you set $address to either the value from the $_POST array or '' if it's not set.
Use the variables you created, like $email and $contact, rather than re-calling the $_POST variables - they're clearer, shorter variable names.
Use the better MySQLi library, rather than the MySQL library.
Create one connection ($con = ...) to your database at the beginning of your script, and don't create a second one later on, like you do here.
Explicitly specify which connection your queries are running against - you say $q2=mysql_query("SELECT ...") but you should also pass the connection you've constructed,
$q2=mysql_query("SELECT ...",$con).
First of all you want to check if the property isset in your $_POST object:
if(isset($_POST["name"])
second you want to check if the value set is empty
if(isset($_POST["name"] && !empty($_POST["name"]))
now you just have to scale it up to check all your properties it would be handy to move it into a function like this
function ispostset($post_var)
{
if (isset($_POST[$post_var]))
{
if ($_POST[$post_var] != '')
{
return true;
}
else
return false;
}
else
return false;
}

Categories