SitePoint Sponsor

User Tag List

Results 1 to 13 of 13
  1. #1
    SitePoint Member
    Join Date
    May 2012
    Posts
    7
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    What is wrong with my code?

    WHAT is WRONG WHIT THIS CODE?

    PHP Code:
    if (isset($_POST['submit'])) {
    $errors = array();

    $required_fields = array('menu_name''position''visible');
    foreach(
    $required_fields as $fieldname) {
    if (!isset(
    $_POST[$fieldname]) || (empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) { 
    $errors[] = $fieldname
    }
    }
    $fields_with_lengths = array('menu_name' => 30);
    foreach(
    $fields_with_lengths as $fieldname => $maxlength ) {
    if (
    strlen(trim(mysql_prep($_POST[$fieldname]))) > $maxlength) { $errors[] = $fieldname; }
    }

    if (empty(
    $errors)) {
    // Perform Update
    $id mysql_prep($_GET['subj']);
    $menu_name mysql_prep($_POST['menu_name']);
    $position mysql_prep($_POST['position']);
    $visible mysql_prep($_POST['visible']);

    $query "UPDATE subjects SET 
    menu_name = '
    {$menu_name}', 
    position = 
    {$position}
    visible = 
    {$visible} 
    WHERE id = 
    {$id}";
    $result mysql_query($query$connection);
    if (
    mysql_affected_rows() == 1) {
    // Success
    $message "The subject was successfully updated.";
    } else {
    // Failed
    $message "The subject update failed.";
    $message .= "<br />"mysql_error();
    }

    } else {
    // Errors occurred
    $message "There were " count($errors) . " errors in the form.";
    }

    I have a form with ID, MENU_NAME, POSITION and VISIBLE and i'm trying to validate the form by checking if the fields are empty OR set with foreach and if i'ts empty make $errors[] = $fieldname.. And I test IF errors is empty execute code if it has something in it don't.. but its not listening to me... Can you help me? Thank you in advance !
    Last edited by TheRaptor; May 10, 2012 at 11:24. Reason: reformatted code with [PHP] tags

  2. #2
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,129
    Mentioned
    152 Post(s)
    Tagged
    0 Thread(s)
    I think you want to use sizeof($errors) == 0 instead of empty($errors)

  3. #3
    SitePoint Member
    Join Date
    May 2012
    Posts
    7
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Can't get it to work... here is my idea:

    PHP Code:
    $errors = array();
    $names = array("James","Etel","");
                    
    foreach(
    $names as $name){
         if(empty(
    $name)){
        
    $errors[] = "You have an unset name in your array";
        }
    }

    if(empty(
    $errors)){
        echo 
    "OK";
    }else{
        echo 
    "You have " count($errors) . " In your form. <br />  review the folowing fields:";
             foreach (
    $errors as $error){
             echo 
    $error "<br />";
              }

    should return error... Right?

  4. #4
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,129
    Mentioned
    152 Post(s)
    Tagged
    0 Thread(s)
    I think you need to replace
    Code:
    if(empty($errors)){
    With
    Code:
    if(sizeof($errors) == 0){

  5. #5
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,129
    Mentioned
    152 Post(s)
    Tagged
    0 Thread(s)
    Okay, so I was incorrect, empty() should work on an array. However, I still think sizeof() is likely a better candidate, simply for the fact that empty() looks to have changed recently between 5.3 and 5.4.

  6. #6
    SitePoint Member
    Join Date
    May 2012
    Posts
    7
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I have to check the change log... but i tried with sizeof and empty it returns no error end submits the form.... I should look for other single page form submission methods.... right?

  7. #7
    SitePoint Enthusiast OMGCarlos's Avatar
    Join Date
    Apr 2012
    Location
    Boston, MA
    Posts
    91
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    "" actually equals something...it equals an empty string which is totally different from an empty variable! If you check empty($name) it will NOT be empty, as it actually contains a value (that is, it contains a value of no value...I know, confusing).

    Try this:
    Code:
    if(empty($name) || $name =='')

  8. #8
    SitePoint Enthusiast OMGCarlos's Avatar
    Join Date
    Apr 2012
    Location
    Boston, MA
    Posts
    91
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Wow, that's a good attitude to take You definitely always want to learn best practices early on. Now that you mention it, the simplest way of doing it would be:

    if( !array_key_exists( $fieldname, $_POST[] ) )

    That will reduce your if statement to just a single condition. Although, I think it might actually be a million millionth of a second slower...

  9. #9
    SitePoint Member
    Join Date
    May 2012
    Posts
    7
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This way it should work but if there is a value in the error array the form still gets submitted and the if statement doesn't work..

    PHP Code:
    if (isset($_POST["submit"])){
                    
    $errors_array = array();
                    
    $required_fields = array("menu_name""position""visible");
                    foreach(
    $required_fields as $fieldname){
                        if(empty(
    $_POST[$fieldname]) || $_POST[$fieldname] == "" ){
                            
    $errors_array[] = $fieldname;
                    }
                    
                    if(empty(
    $errors)){ //no error
                        //form validation
                    
    }else{
                        
    //error
                    
    }
            } 
    and when i lave the menu_name field empty $errors_array[0] == manu_name string witch is not empty but php still considers it empty (line 9) and submits an empty string in the database... WHY?

    BTW thanks for helping me out learning php alone is a pain... Glad I found sitepoint...

  10. #10
    SitePoint Member
    Join Date
    May 2012
    Posts
    7
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sorry for deleting that post.. the code was......functioning incorrectly.. But i'm jumping to test you idea!

    Quote Originally Posted by OMGCarlos View Post
    Wow, that's a good attitude to take You definitely always want to learn best practices early on. Now that you mention it, the simplest way of doing it would be:

    if( !array_key_exists( $fieldname, $_POST[] ) )

    That will reduce your if statement to just a single condition. Although, I think it might actually be a million millionth of a second slower...

  11. #11
    SitePoint Evangelist
    Join Date
    Oct 2005
    Location
    Michigan, USA
    Posts
    434
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    In your last example you're using $errors_array but checking if(empty($errors)) - not the same variable.

    By the way, in PHP empty() is true for many cases. An empty string is "empty".
    PHP Code:
    $str '';
    var_dump( empty( $str ) ); // true 
    - Robert

  12. #12
    SitePoint Member
    Join Date
    May 2012
    Posts
    7
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This works...

    PHP Code:
    $form_action "SAME PAGE";
    $field_manu_name "About us";
    $field_position 2;
    $field_visible 1;


    if (isset(
    $form_action)){ 
                    
    $errors_array = array(); 
                    
    $required_fields = array($field_manu_name$field_position$field_visible); 
                        foreach(
    $required_fields as $fieldname){ 
                            if(empty(
    $fieldname) || $fieldname == "" ){ 
                                
    $errors_array[] = $fieldname
                            } 
                        } 
                    
                    if(empty(
    $errors_array)){ //no error 
                        //form validation 
                        
    echo "OK";
                    }else{ 
                        
    //error 
                        
    echo "ERROR";
                    } 
                    
        } 
    But when I use it with a form something goes wrong.... I have to get this working.. but I need to sleep first because i'm tired I already submitted bad code 2 times sorry about that... And thanks for everyone's help...

  13. #13
    SitePoint Member
    Join Date
    May 2012
    Posts
    7
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I rewrited the code.... and now it works... see if you can spot the difference between this and the first code i submitted...

    PHP Code:

        
    if (isset($_POST["submit"])){ 
                    
    $errors_array = array(); 
                    
    $required_fields = array("menu_name""position""visible"); 
                        foreach(
    $required_fields as $fieldname){ 
                            if(empty(
    $_POST[$fieldname]) || $_POST[$fieldname] == "" ){ 
                                
    $errors_array[] = $fieldname
                            } 
                        } 
                    
                    
    //field length
                    
    $fields_with_lengths = array("menu_name" => 30);
                              
    $errors_array check_max_field_lengths($fields_with_lengths);
                    
                    
                    if(empty(
    $errors_array)){ 
                        
                        
    //form validation
                        //perform update
                        
    $id mysql_prep($_GET["subj"]);
                        
    $menu_name mysql_prep($_POST["menu_name"]);
                        
    $position mysql_prep($_POST["position"]);
                        
    $visible mysql_prep($_POST["visible"]);
                        
                        
    $query "UPDATE subjects SET
                                    menu_name = '
    {$menu_name}',
                                    position = '
    {$position}',
                                    visible = '
    {$visible}'
                                    WHERE id = 
    {$id}";
                        
    $result mysql_query($query$connection);
                            if(
    mysql_affected_rows() == 1){ //mysql query test
                                //success
                                
    $message "The subject was successfully updated";
                                
                            }else{
                                
    //errors
                                
    $message "The subject update failed.";
                                
    $message .= "<br />" mysql_error();
                            }
                        
                    }else{ 
                            
    //errors 
                            
    if(count($errors) == 1){
                                
    $message "there was an error in the submitted form";
                            }else{
                                
    $message "There were " count($errors_array) . " errors in the form";
                            }
                    } 
                    
        } 
    And here is a simple version of the code....

    PHP Code:
    <?php 
    if (isset($_POST["submit"])){ 
                    
    $errors_array = array(); 
                    
    $required_fields = array("username"); 
                        foreach(
    $required_fields as $fieldname){ 
                            if(empty(
    $_POST[$fieldname]) || $_POST[$fieldname] == "" ){ 
                                
    $errors_array[] = $fieldname
                            } 
                        } 
                    
                    if(empty(
    $errors_array)){ //no error 
                        //form validation 
                        
    echo "OK";
                    }else{ 
                        
    //error 
                        
    echo "ERROR";
                    } 
                    
        }
    ?>

    <!--fun.php is the _self -->
    <form name="input" action="fun.php" method="POST">
    Username: <input type="text" name="username" />
    <input name="submit" type="submit" value="Submit" />
    </form>


Bookmarks

Posting Permissions

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