1

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the insight. I think I will go this route.
0
$checkbox1 = $_POST['checkbox_array'];
$selected_checkbox = "";
foreach ($checkbox1 as $checkbox1) 
{
   $selected_checkbox .= $checkbox1 . ", ";
}
$selected_checkbox = substr($selected_checkbox, 0, -2);

// your insert query here.. 

1 Comment

Thanks @chirag, so you are suggesting, I save the elements of the checkbox array in a comma separated fashion in a single column?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.