PHP checkbox array help

Status
Not open for further replies.
So I have an array of checkboxes that get populated for each row in a table like so:
Code:
<input type='checkbox' name='chk[]' value='<?php echo $ID;?>' <?php if($info == 'YES') echo 'checked'; ?>/>

Now, I need to post back to the database whether or not the checkbox is checked to update the record.

This works as long as the checkbox is checked like so:
Code:
$info = $this->input->post('chk');
foreach ($info as $ID)
			{
				$this->db->query("UPDATE ModelEvents
									SET info = 1
									WHERE ID = $ID
									AND EventID = $EventID");
			}

The HTML specification says that the checkbox will not post if it isn't checked. How do I update those records??
 

obrienm

Wise, Aged Ars Veteran
120
A couple of ideas come to mind but neither seem all that pretty.

1) If we're not talking about a huge amount of rows could you update all rows to 0 (or whatever the unchecked state is) and then proceed as normal with your existing update code to set the IDs that you want checked?

2) Being that it appears your ID values are coming from the database already could you generate an array from the checked values and do another update query where the IDs are not within the array values?
 
KrispyK":1a9puulg said:
Code:
            $this->db->query("UPDATE ModelEvents
                           SET info = 0
                           WHERE ID NOT IN (".implode(',',$info).")
                           AND EventID = $EventID");

Of course, you should really be using bound parameters to avoid injection....

I'll try something along those lines. As for the injection, once I figure out the correct SQL statement, I'm going to use the Active Record db class in CodeIgniter's framework and it'll take care of escaping the values.

Thanks!
 
Status
Not open for further replies.