开发者

codeigniter Problem - Checkbox group

I’m fairly new to OOPHP and CI so I had a quick question that could be an easy answer for some people.

I have a form right now with about 100 checkboxes all with the same name so they will submit as an array of numbers.

I also have a table named tag_restaurant_rel which is a relational table that is setup as InnoDB and both restaurant_id and tag_id are Foreign Keys relating to the corresponding columns in two other tables.

The form will be submitted with 1 restaurant_id and several tag_id’s.

In the tag_restaurant_rel table there is a record for each tag_id in the array all with the same restaurant_id from the form.

What I need to h开发者_高级运维appen is for the form to be submitted and depending on the array of checkbox values the tag_restaurant_rel table will need to delete the records that are not in the array and create a new record for each tag_id in the array.

I’m mostly curious in the most efficient way to do this OOP and CI style.


If there is no id for the rag_restaurant_rel table or the id does not matter (AI int or something that isn't referenced elsewhere), I would think the simplest way would be to wipe the table where restaurant_id = whatever and then just insert all of the submitted IDs.

I am not very familiar with CI and I don't know how you're interacting with the database, so from the script side of things I don't have much input. If you're using MySQL, I believe that prepared statements are highly efficient for multiple inserts, so maybe that would be the way to go. As for OOP, again, depending on how you're interacting with the database, it would just be a matter of adding 1, 2, or 3 methods.

Something like:

public function updateRestaurantRelations($restId, $tagArray)
{
//called from your script
if($this->wipeCurrentTags($restId)){
    if($this->addNewTags($restId, $tagArray)){
        return true;
    }
}
return false;
}
private function wipeCurrentTags($restId)
{
//perform query here or call delete method
//return true on success and false on failure
}
private function addNewTags($restId, $tagArray)
{
//perform query here or build prepared statement loop here or call insert method
//return true on success and false on failure
} 

Again I do not know how compatible that would be with CI.

You might also consider adding the POSTed tags first (or selecting the current ones before delete) so that if there is an error on the insert, your table isn't wiped clean of all the tags that were already in the db (or you would be able to restore them).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜