Hey everyone,

I am working on a form to update my db.

I am using a foreach to get field names and values.

foreach($_POST as $items => $values) {

echo 'items: '.$items.' - values: '.$values.'<br/>';

}

If a field is left blank, it doesn't show up in my foreach.

I need to know if a field is left blank, that way i can use an if statement and insert a NULL value in my db.

I am aware of the empty function, but it doesn't work in my foreach.

foreach($_POST as $items => $values) {

if(empty($values)) { echo 'foobar is empty'; }

echo 'items: '.$items.' - values: '.$values.'<br/>';

}

Thank you!

    What kind of form element are you talking about? An <input type="text"> type of field?

    If so, those fields should still be POST'ed even if they're left blank (unless you have some sort of client-side scripting that disables those fields before the form is submitted). Do a [man]print_r/man on $_POST and post the output here, that way we can see what kind of data is being sent to the PHP script.

      Yes, they are all input text.

      Here are the relevant part of the print_r.

      [day_1] => 69 [week_1] => 699 [month_1] => 2999 [minnights_1] => 4 [notes_1] => [day_2] => 69 
      

      notes_1 is an empty field.

      if I do:

      
      if($empty($_POST['notes_1'])) { echo 'empty'; } // PRINTS OUT 'EMPTY'
      
      

      It seems like if I used a foreach items as values, only items that aren't empty will loop, and the empty fields are disregarded.

        Are you doing anything to $_POST before this loop? The foreach shouldn't skip an element just because its value is empty.

        Presumably you know what the full set of fields should be; you can supply defaults. One method I've used is this:

        $expected_fields = array('field1', 'field2', 'field3', 'field4', ...);
        $expected_fields = array_fill_keys($expected_fields, null);
        // So $expected_fields is an array representing a completely blank form (all fields null)
        $_POST = $_POST + $expected_fields; // See the manual section on array operators.
        // now $_POST has an element for every field, including blank ones.
        

          I got it figured out. Thanks to the both of you.

          have a good day

            Write a Reply...