Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 12 of 12
  1. #1
    Senior Coder
    Join Date
    Apr 2010
    Posts
    1,555
    Thanks
    75
    Thanked 105 Times in 104 Posts

    Foreach error won't stop script

    I am using the script below to check first for blank fields and then for any fields that has a string length of less than 4 characters.
    However if I submit blank fields or anything with say 2 characters, it still shows the errors but processes the script and inserts the values of everything in the database. I am confused to why? I tried add a die; after the if statement, inside of the foreach and that shuts down everything.


    PHP Code:
      $notice = array('username'=>'Username''password'=>'Password''charname'=>'Charname''email'=>'Email''select_class'=>'Class''fullname'=>'Your Name''fulladdress'=>'Your Address''dob'=>'Date of Birth');
        foreach (
    $_POST as $key => $item)
        {
               if (empty(
    $item))
               {
                       
    printf("%s is required, please add content<br />"$notice[$key]);
               }

        }

        
    $notice2 = array('username'=>'Username''password'=>'Password''charname'=>'Charname''email'=>'Email''fullname'=>'Your Name''fulladdress'=>'Your Address');
        foreach (
    $_POST as $key2 => $item2)
        {
               if (
    strlen($item2) < '4')
               {
                       
    printf("%s must be at least 4 characters.<br />"$notice2[$key2]);
               }

        } 
    Been a sign maker for 7 years. My business:
    American Made Signs

  • #2
    Senior Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    3,469
    Thanks
    13
    Thanked 361 Times in 357 Posts
    if I submit blank fields or anything with say 2 characters, it still shows the errors but processes the script and inserts the values of everything in the database. I am confused to why?
    why should the foreach() stop the script? it’s just a loop that prints an error message.

    you need to tell the script to stop executing explicitly using a condition.
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer

  • #3
    Senior Coder
    Join Date
    Apr 2010
    Posts
    1,555
    Thanks
    75
    Thanked 105 Times in 104 Posts
    I can't figure out how to end it after it displays all errors instead of just one.
    Been a sign maker for 7 years. My business:
    American Made Signs

  • #4
    Regular Coder Linux_Sage's Avatar
    Join Date
    Mar 2014
    Location
    Sterling,VA
    Posts
    106
    Thanks
    0
    Thanked 10 Times in 10 Posts
    To break out of a loop you'd normally use
    PHP Code:
    break; 
    However it's hard to tell what you need here because I can't tell where exactly you're running the insertion. Essentially you'd want to set it up to where if errors were found then don't insert any records and report what was found.

  • #5
    Senior Coder CFMaBiSmAd's Avatar
    Join Date
    Oct 2006
    Location
    Denver, Colorado USA
    Posts
    3,146
    Thanks
    2
    Thanked 333 Times in 325 Posts
    When validating data, it's customary to set a flag to indicate a validation error, then to check if this flag is set or not to determine if you should use the submitted data.

    Also, it's good programming practice to separate your processing logic from your display logic. The processing logic produces data in php variables that the display logic uses.

    You can kill two birds with one stone by using an array that serves as both the error flag and holds the validation error messages. Instead of printing each error message at the time you detect the error(s), store each error messaged as an entry in an $error array. Then, after all the validation tests have been ran, if the array is empty, you know there were no validation errors and you can use the submitted data. If the array is not empty, you would loop over the entries in it to print the error messages.
    If you are learning PHP, developing PHP code, or debugging PHP code, do yourself a favor and check your web server log for errors and/or turn on full PHP error reporting in php.ini or in a .htaccess file to get PHP to help you.

  • #6
    Senior Coder
    Join Date
    Apr 2010
    Posts
    1,555
    Thanks
    75
    Thanked 105 Times in 104 Posts
    @ CFMaBiSmAd, I am not good at arrays, so not sure how to set it up separate.

    @ Linux_Sage, this is the coding

    PHP Code:
    if (isset($_POST['submit'])) {
          extract($_POST);
          
          $username = $_POST['username'];
          $password = $_POST['password'];
          $charname = $_POST['charname'];
          $email = $_POST['email'];
          $class = $_POST['select_class'];
          $strength = $_POST['strength'];
          $attack = $_POST['attack'];
          $defense = $_POST['defense'];
          $dexterity = $_POST['dexterity'];
          $fullname = $_POST['fullname'];
          $fulladdress = $_POST['fulladdress'];
          $dob = $_POST['dob'];
          $password2 = md5($password);
          
          /*
          /////////////////////////////////////////
          Start checks for error fields
          ////////////////////////////////////////
          */
          
          $notice = array('username'=>'Username', 'password'=>'Password', 'charname'=>'Charname', 'email'=>'Email', 'select_class'=>'Class', 'fullname'=>'Your Name', 'fulladdress'=>'Your Address', 'dob'=>'Date of Birth');
        foreach ($_POST as $key => $item)
        {
               if (empty($item))
               {
                       printf("%s is required, please add content<br />", $notice[$key]);
               }

        }

        $notice2 = array('username'=>'Username', 'password'=>'Password', 'charname'=>'Charname', 'email'=>'Email', 'fullname'=>'Your Name', 'fulladdress'=>'Your Address');
        foreach ($_POST as $key2 => $item2)
        {
               if (strlen($item2) < '4')
               {
                       printf("%s must be at least 4 characters.<br />", $notice2[$key2]);
               }

        }
          

          
          if ($class == "choose") {
            echo "Please select a character class. <br />";
            die;
          }



          /*
          ///////////////////////////////
          End checks for error fields
          //////////////////////////////
          */
          
        $con=mysqli_connect("localhost","xxxx","xxxx","xxxx_xxx");
    // Check connection
    if (mysqli_connect_error())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }
          
        $sql = mysqli_query($con,"INSERT INTO rod_AllUsers (username, password, email, fullname, address, birthday, regdate)
          VALUES ('$username','$password2','$email','$fullname','$fulladdress','$dob','NOW()')");
          
         if(!$sql)
      {
      die('Error: ' . mysqli_error($con));
      }
    echo "1 record added";

    mysqli_close($con);

          ?>
          
          Your account has been created.<br />
          <?php
        
    }
        else {
    Been a sign maker for 7 years. My business:
    American Made Signs

  • #7
    Regular Coder Arcticwarrio's Avatar
    Join Date
    May 2012
    Location
    UK
    Posts
    738
    Thanks
    20
    Thanked 85 Times in 85 Posts
    first of all
    PHP Code:
           extract($_POST); 
    is the same as

    PHP Code:
          $username $_POST['username'];
          
    $password $_POST['password'];
          
    $charname $_POST['charname'];
          
    $email $_POST['email'];
          
    $class $_POST['select_class'];
          
    $strength $_POST['strength'];
          
    $attack $_POST['attack'];
          
    $defense $_POST['defense'];
          
    $dexterity $_POST['dexterity'];
          
    $fullname $_POST['fullname'];
          
    $fulladdress $_POST['fulladdress'];
          
    $dob $_POST['dob'];
          
    $password2 md5($password); 
    you don't need both.

    you would need this line tho
    PHP Code:
    $password2 md5($password); 

    as for errors
    add the error to a variable and print at the end

    PHP Code:
     $notice = array('username'=>'Username''password'=>'Password''charname'=>'Charname''email'=>'Email''select_class'=>'Class''fullname'=>'Your Name''fulladdress'=>'Your Address''dob'=>'Date of Birth');
    $error '';//make sure the variable is empty
        
    foreach ($_POST as $key => $item)
        {
               if (empty(
    $item))
               {
                       
    $error .= "$notice[$key] is required, please add content<br />";
                               
    // the . before the = adds it to the end of whats already stored in the variable
               
    }
               if (
    strlen($item) < '4')
               {
                        
    $error .= "$notice[$key] must be at least 4 characters.<br />";
               }

        } 
    There are 10 types of people on CodingForums,
    Those who understand Binary and those who dont.
    Get Cloud Hosting now from only£59 / month

  • #8
    Senior Coder
    Join Date
    Apr 2010
    Posts
    1,555
    Thanks
    75
    Thanked 105 Times in 104 Posts
    This is what I have and it's a failure. Still inserts the new account into the database....

    PHP Code:
    $notice = array('username'=>'Username''password'=>'Password''charname'=>'Charname''email'=>'Email''select_class'=>'Class''fullname'=>'Your Name''fulladdress'=>'Your Address''dob'=>'Date of Birth');
    $error '';//make sure the variable is empty
        
    foreach ($_POST as $key => $item)
        {
               if (empty(
    $item))
               {
                       
    $error .= "$notice[$key] is required, please add content<br />";
                               
    // the . before the = adds it to the end of whats already stored in the variable
               
    }
               if (
    strlen($item) < '4')
               {
                        
    $error .= "$notice[$key] must be at least 4 characters.<br />";
               }

        }
          
           if (
    $error == 0) {
               echo 
    "1 record added, Your account has been created.<br />";
             }
             else {
               die;
             } 
    Been a sign maker for 7 years. My business:
    American Made Signs

  • #9
    Regular Coder
    Join Date
    Sep 2002
    Posts
    462
    Thanks
    0
    Thanked 20 Times in 20 Posts
    Code:
    $notice = array('username'=>'Username', 'password'=>'Password', 'charname'=>'Charname', 'email'=>'Email', 'select_class'=>'Class', 'fullname'=>'Your Name', 'fulladdress'=>'Your Address', 'dob'=>'Date of Birth');
    
    $error = '';
    
    $Process_Post = true;
    
    //----- Validation Loop Start -----//
        foreach ($_POST as $key => $item)
        {
               if (empty($item)) {
                       $error .= "$notice[$key] is required, please add content<br />";
                      $Process_Post = false;
                      //add break to stop loop and display individual error
               }
    
               if (strlen($item) < '4'){
                        $error .= "$notice[$key] must be at least 4 characters.<br />";
                      $Process_Post = false;
                      //add break to stop loop and display individual error
               }
    
        }
    //----- Validation Loop End -----//
    
    
    
    //----- Start Processing -----//
           if ( $Process_Post) {
              //----- Processing Loop Start -----//
               echo "1 record added, Your account has been created.<br />";
    
              //----- Processing Loop End -----//
             }
    You need to validate separately from processing...
    NO Limits!! DHCreationStation.com
    ------------------------------------------------------------
    For projects using MediaTypes (MIMETypes) visit E-BAM.net -(updated weekly)

    Broken items wanted for tinkerin'! PostItNow@BrokenEquipment.com
    Global Complaint Dept.

  • #10
    Senior Coder CFMaBiSmAd's Avatar
    Join Date
    Oct 2006
    Location
    Denver, Colorado USA
    Posts
    3,146
    Thanks
    2
    Thanked 333 Times in 325 Posts
    Code:
    if ($error == 0) {
    ^^^ Your $error variable is a string. When you try to compare it with a number, it's converted to a number and all strings that don't start with numbers will be a zero when treated as a number.

    If you initialized $error = '';, why wouldn't you use that in your test?

    Code:
    if ($error == '') {
    If you are learning PHP, developing PHP code, or debugging PHP code, do yourself a favor and check your web server log for errors and/or turn on full PHP error reporting in php.ini or in a .htaccess file to get PHP to help you.

  • #11
    Senior Coder
    Join Date
    Apr 2010
    Posts
    1,555
    Thanks
    75
    Thanked 105 Times in 104 Posts
    @C1onewolf, doesn't work all I get is blank. The page graphics and everything loads but blank text?

    @CFM, ah I remember now, I didn't convert it into a number to be checked by the string. I forgot about that part.
    Been a sign maker for 7 years. My business:
    American Made Signs

  • #12
    Senior Coder
    Join Date
    Apr 2010
    Posts
    1,555
    Thanks
    75
    Thanked 105 Times in 104 Posts
    Seeing how this isn't possible to fix or do in PHP, I'll revert to using JS which does work in a sense.
    Been a sign maker for 7 years. My business:
    American Made Signs


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •