Jump to content

Why is error checking being skipped upon post?


greenace92
Go to solution Solved by greenace92,

Recommended Posts

First, I'd like to apologize for my behavior, I didn't really "do anything wrong per se" I just get impulsive sometimes haha bad start

I am so close to finishing this website, which I will use to sell myself as a person who fixes computers

 

I am stuck on this problem, for all the pages

 

Either I can error check but data is not recorded in the tables

 

Or the error checking works but data is not recorded

 

The problem seems to be "triggered" by removing $errors[]="";

 

Also I'd like to say hello to QuickOldCar

 

Anyway here is the php parts of a single web page, this problem is shared on all of them except the index page which has successful error checking, session data retrieval and redirecting / updating data

 

I've spent days trying to fix this amongst other things (pretty sad right) this is literally one of the final problems to be solved before I'm ready to get his website indexed / advertise it

Thanks for any help

<?php 
ob_start();
  session_start();
  
  global $nameErr,$emailErr,$commentsErr,$hourErr,$minuteErr;
  global $name,$comments,$email,$hour,$minute;

  mysqli_report(MYSQLI_REPORT_ALL);
error_reporting(E_ALL);
error_reporting(-1);

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

$servername = "localhost";
$username = "  ";
$password = "  ";
$dbname = "  ";

global $link;
$link = new mysqli("$servername", "$username", "$password", "$dbname");


if($_SERVER['REQUEST_METHOD']=='POST'){

$errors = array();
  
    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 = "The form of the name entered is not acceptable"; 
     }
   }
   
if (empty($_POST["email"])) {
     $emailErr = "An email is required";
   } else {
   $email = test_input($_POST["email"]);
   }
   
if (empty($_POST["comments"])) {
     $commentsErr = "A comment is required.";
   } else {
     $comments = test_input($_POST["comments"]);
     // check if name only contains letters and whitespace
   }
   $test = $_POST['hour'];
   $test1 = '$test';
if (empty($_POST['hour'])) {
     $hourErr = "Please specify an hour between 12 and 8";
   } else {
      if (ctype_digit($_POST['hour'])) {
       $hour = test_input($_POST['hour']);
     }else {
      $hourErr = "Only numbers are allowed"; 
      }
   }
if (empty($_POST['minute'])) {
     $minuteErr = "Please specify a minute between 1 and 60";
   } else {
      if (ctype_digit($_POST['minute'])) {
        $minute = test_input($_POST['minute']);
     }
     else {
     $minuteErr = "Only numbers are allowed"; 
     }
   }

if(empty($errors)){

$link = new mysqli("$servername", "$username", "$password", "$dbname");

$name = test_input($_POST['name']);
$email = test_input($_POST['email']);
$comments = test_input($_POST['comments']);
$hour = test_input($_POST['hour']);
$minute = test_input($_POST['minute']);
        // use the submitted data here... insert into database, send email, ...


$stmt = mysqli_prepare($link, "INSERT INTO Dropoff VALUES (?,?,?,?,?)");
$stmt->bind_param('sssii',$name,$email,$comments,$hour,$minute);

$stmt->execute();

$to = '  ';

$subject = 'Dropoff scheduled';

$message = "Check the database";

$message = wordwrap($message,70,"\r\n");

$headers = 'From: service@jakes-bytes.us'."\r\n\r\n";

mail($to,$subject,$message,$headers);

$to = $email;

$subject = 'Jakes Bytes Your Dropoff Has Been Scheduled';

$message = "Thank you for choosing Jakes Bytes computer repair shop.\r\n\r\nAttached is the information you have sent.\r\n\r\n
\r\n\r\nBelow is our address. Look for the Greek letters on our building.\r\n\r\nJake's Bytes is a private business. Please call upon arrival.\r\n\r\nThank you.\r\n\r\n169 Highgate Ave. Buffalo, NY 14215\r\n\r\nJake's Bytes is a property of Normalbus";

$message = wordwrap($message,70,"\r\n");

$headers = 'From:   '."\r\n\r\n";

mail($to,$subject,$message,$headers);

   // set up a status message to be displayed one time
          $_SESSION['status_message'] = "Drop off scheduled successfully";
        
        // after successfully processing any post form data, redirect to the same exact url of this page to clear the post data
        $host  = $_SERVER['HTTP_HOST'];
        $uri   = $_SERVER['REQUEST_URI']; // the path/file?query string of the page
        header("Location: http://$host$uri");
        exit;      
         

$link->close();

}
}   
?>
<HTML>
<html break>
<?php

if(!empty($errors)){
    foreach($errors as $error){
        echo '<span style="color: red">'.htmlspecialchars($error).'</span>'.'</br>'.'</br>';
       
    }
    } 
    
    if(isset($_SESSION['status_message'])){
    echo '<span style="color: #ccfb5d">'.htmlspecialchars($_SESSION['status_message']).'</span>'.'</br>'.'</br>';
    unset($_SESSION['status_message']); // clear the message
}
?>
<html resume>
</html>

Awe it's too bad the code paste box doesn't have highlighting, I've been spending time at other PHP forums and codingforums uses highlighting which is very helpful

Edited by mac_gyver
link removed
Link to comment
Share on other sites

Hello to you as well.

 

If are storing errors in $errors array you can just add to it something like this

$errors = array();

if (empty($_POST["name"])) {
     $errors['name'] = "Name is required";
   } else {
     $name = test_input($_POST["name"]);
     // check if name only contains letters and whitespace
     if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
       $errors['name'] = "The form of the name entered is not acceptable";
     }
   }
Link to comment
Share on other sites

$nameErr = "The form of the name entered is not acceptable";

along with all your other errors needs to be changed to

$errors[]= "The form of the name entered is not acceptable";

 

I don't understand what you mean?

 

How would the errors be identified individually?

 

Oh wait... nevermind I understand, I wonder why that is?

 

I followed w3schools, which funny enough another website calls them "W3Fools" eg. don't use that site

 

This is pulled from their example here

$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
   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";
     }
   }

I need to show individual errors

Also thank you for the fast responses

 

See it works here (attached image) but again it doesn't post, just refreshes the page

 

p.s. Hello QuickOldCar happy to hear from you

post-164367-0-93995000-1419773897_thumb.png

Edited by greenace92
Link to comment
Share on other sites

Sorry for the confusion, that image is not for the code above, I was just trying to clarify what I was looking to achieve.

 

The form is always there, if you hit submit without filling in the fields, the errors should appear.

 

I have these lines <?php echo $errors['hour'];?> next to an hour field for example, now I get error messages that say "undefined variable $errors" wherever I try to echo the error

 

I don't understand how I would identify an error without specifying it

 

That's what I don't get about the first response by NotionCommotion

 

$nameErr = "The form of the name entered is not acceptable";

 

along with all your other errors needs to be changed to

 

$errors[]= "The form of the name entered is not acceptable";

 

I need to tell a person what part is incorrect and excuse me if that is what NotionCommotion just showed me

Link to comment
Share on other sites

Alright so the problem has been solved thanks to both of your suggestions however it does not work properly

When I declare the $errors[]=""; so that they are not undefined, these take up space, pushing down my fields, what is up with that?

 

Also when I purposely leave the fields blank, there are double errors displayed...

 

Where would I put the empty variables? So that they aren't shown eg. take up space but also are not executed until post?

 

See the actual image of this example

 

This is great, it's so frustrating to go nowhere you know? Like smashing your head into a brick wall over and over... the difference seems insignificant like "oh look at that, it actually worked" but it is a great feeling

 

Thanks for the help

 

 

post-164367-0-07146600-1419775897_thumb.png

post-164367-0-99682000-1419775902_thumb.png

post-164367-0-68956700-1419775908_thumb.png

Link to comment
Share on other sites

Your original script at the end just displays the errors as a group.  Note that this is typically how I do it.  I agree that error prompts at the individual fields are nice, and I use jQuery validation plugin for client "nice" validation before validating serverside, so most people don't see the list of errors.

if(!empty($errors)){
    foreach($errors as $error){
        echo '<span style="color: red">'.htmlspecialchars($error).'</span>'.'</br>'.'</br>';

    }
}

As for as $errors[]=""; goes, you shouldn't be doing this.  Doing so just adds another element to the array.  Even though PHP doesn't require, I always define an empty array using $errors=array(); before adding elements to it.

 

Get to know and appreciate var_dump().  Or, if you prefer (I often do), use the following:

echo('<pre>'.print_r($errors,1).'</pre>');
Link to comment
Share on other sites

  • Solution

Oh my GOD!!! WOOOOOOOOOOOOO
 

He hath risen!

 

Thank you guys, very much.

 

Glad I overcame my ego...

 

The solution was to declare $errors as a global variable at the top, then using $errors['name']="something"; I could echo them in the right location using <?php echo $errors['name'] ;?>

 

Also this is redundant

 

if(!empty($errors)){
    foreach($errors as $error){
        echo '<span style="color: red">'.htmlspecialchars($error).'</span>'.'</br>'.'</br>';
       
    }
    }

 

Boom! Case closed... bring the cows home

Link to comment
Share on other sites

I have these lines <?php echo $errors['hour'];?> next to an hour field for example, now I get error messages that say "undefined variable $errors" wherever I try to echo the error

 

 

someone in the other php help forum showed how to reference the associative error array elements so that they won't produce php errors if the validation error isn't set -

 

<?php if(isset($errors['name'])){ echo $errors['name']; } ?> 

 

 

someone in the other php help forum even went to the trouble of taking the page layout you were shown and posted a working example using it, setting associative error array messages and displaying the errors next to each form field they apply to.

 


 

When I declare the $errors[]="";

 

why do you even have that line in your code? it wasn't in the original page layout you were shown.

 


 

The solution was to declare $errors as a global variable at the top

 

 

i'm pretty sure that someone else in the other help forum mentioned that the global keyword, the way you are using it, doesn't do anything (and in the case where it does do something, inside of a function definition, it shouldn't be used as it results in spaghetti code.) 

 


 

edit: lastly, why do you have an ob_start() statement in your code? all that typically results in hiding problems in code and messes with output your script tries to display.

Edited by mac_gyver
more info
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.