1

There are multiple checkbox about 50+ for user access, checkbox are like follows;

<input name="PREFIX_1" type="checkbox">
<input name="PREFIX_2" type="checkbox">
<input name="PREFIX_3" type="checkbox">
...........

I have multiple checkbox with its respective values which I loop through to add/update the values in the database, which is like follows:

foreach ($_POST as $field => $value ) {
   if ( preg_match('/^PREFIX_/', $field) ) {
       $access = isset($value)?'1':'0';
       $file = substr($field, 4);
       $this->db->query('UPDATE_DESIRED_TABLE');
   }
}

The problem is when I add/update the values in the database by using loop foreach ($_POST as $field => $value ) and checking the prefix, I only get values of checkbox that are checked and the values of data that are not checked are not in the $_POST data.

And, I don't get any values which are not checked, which is not even the name of that checkbox. In other words only those values are set which are checked.

Now I have to change the value of all the data in the database by comparing both the data in the database and from the post data.

How can I solve this?

Regolith
  • 2,944
  • 9
  • 33
  • 50

2 Answers2

1

You would need to send hidden inputs along with the checkboxes like this:

<form action="" method="post">
    <input type="hidden" id="PREFIX_1_" name="PREFIX_1"  value="0">
    <input type="checkbox" id="PREFIX_1" name="PREFIX_1" value="1" />

    <input type="hidden" id="PREFIX_2_" name="PREFIX_2" value="0">
    <input type="checkbox" id="PREFIX_2" name="PREFIX_2" value="1" />

    <input type="hidden" id="PREFIX_3_" name="PREFIX_3" value="0">
    <input type="checkbox" id="PREFIX_3" name="PREFIX_3" value="1" />

    <input type="submit" name="sub" value="Go" />

</form>

However you cant use the isset anymore with this, change PHP like this:

if(isset($_POST['sub']))
{
    foreach ($_POST as $field => $value ) 
    {
        if ( preg_match('/^PREFIX_/', $field) ) 
        {          
           $access = $value;
           $file = substr($field, 4);
           $this->db->query('UPDATE_DESIRED_TABLE');
        }
    }
}
Amit Joshi
  • 1,334
  • 1
  • 8
  • 10
0

Considering you know the number of checkbox, stored in example in $checkBoxCount, you might use this kind of loop :

for ($i = 1; $i <= $checkBoxCount; $i++)
{
    $access = ((isset($_POST["PREFIX_" . $i])) ? ('1') : ('0')));
    //manage DB
}
Cid
  • 14,968
  • 4
  • 30
  • 45