简体   繁体   中英

Editing checkboxes data in php and updating the rows in mysql

I have a group of checkboxes as below, as part of a larger form, in the view.

<input type = "checkbox" value = "1" name = "checkbox_array[]" /> Checkbox 1
<input type = "checkbox" value = "2" name = "checkbox_array[]" /> Checkbox 2
<input type = "checkbox" value = "3" name = "checkbox_array[]" /> Checkbox 3
<input type = "checkbox" value = "3" name = "checkbox_array[]" /> Checkbox 3

Say I check Checkbox 2 and Checkbox 4 and click submit. To save I loop through the checkbox_array[] as below, in the controller.

$checkbox_array = $this -> input -> post('checkbox_array', TRUE)

<?php for($i=0;$i<count($checkbox_array);$i++){
$users = new User();
$users -> role_id = $checkbox_array[$i];
//Amongst other form data
$users -> save();
}?>

This saves the data in the db as:

id role_id 
1    2
2    4

Using the same view, I intend to edit the data saved. So say now I want to check Checkbox 1, uncheck Checkbox 2, check Checkbox 3, retain Checkbox 4. such that I intend to have below in the db.

id role_id 
1    1
2    3
3    4

I am at a loss however how to do the update. I had been thinking of getting the saved array from the db, doing an inarray() search, and inserting the data that is not in the saved array, computationally I do not know about how effective this is.

Is there a mysql function I could use to achieve this, say like replace() , or how else would I be able to achieve the edit?

Thank you.

What I usually end up doing in this situation is first delete all data related to that form in the database (for the specific user, etc) and then insert the data for the checkboxes. It is just far cheaper to delete the data matching the criteria (especially if the WHERE of the delete is on an indexed column) than trying to select and selectively delete them. Not to mention it keeps the code a lot cleaner which over the long-haul for maintenance reasons has its benefits.

Just to be clearer, a DELETE that has WHERE clauses on an index is far cheaper than a SELECT and then a DELETE for those that should not be there and then an INSERT.

$checkbox1 = $_POST['checkbox_array'];
$selected_checkbox = "";
foreach ($checkbox1 as $checkbox1) 
{
   $selected_checkbox .= $checkbox1 . ", ";
}
$selected_checkbox = substr($selected_checkbox, 0, -2);

// your insert query here.. 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM