简体   繁体   中英

CheckBox & Database Update

I have a form as below which allows user to select different collar types. Each checkbox has a collar id which will be submitted when the form is submitted.

领型

Assume that user selected 1st three collars. It would look like this.

领型

Then what I do is add these three collar to my collars table using an insert statement. After that If user wants, he can uncheck the collar types or add new.

Assume that user unchecked the 2nd type as below.

领型

Now the particular row which refer to the 2nd collar type must be deleted from the table. Below images shows the table structure.

在此输入图像描述

Now my problem is When the form is submitted if user has made any changes(checked new checkbox or unchecked any) How can I Insert or delete a row? Do I have to write SELECT statement for each checkbox and see whether that collar id exists?

Help me out with the logic because I'm able to build the code myself according to a given logic.

Thanks

Do I have to write SELECT statement for each checkbox and see whether that collar id exists?

The database can tell you if that ID exists or not, so that does the database.

However, you need to run two queries, one for deletion(s) and one for the insert(s).

I Think if you can save the id or product_id for the particular user than delete its earlier entry and create a new row of that user using that ID. Or Update that row using the id.

I think there are 2 solutions:

  1. You have to SELECT all ids from your table and verify if the checkboxes are selected or not:

     $array = array(); $sql = mysql_query("SELECT collor_id FROM my_table WHERE product_id='x'"); while($row = mysql_fetch_array($sql)) { array_push($array, $row['collor_id']); } if(count($_POST['my_collors']) > 0) { foreach($_POST['my_collors'] as $value) { if(!in_array($value, $array)) { // insert it into db // unset the array value for this collor id } else { // unset the array value for this collor id } } } // foreach remained array value delete them from the db 
  2. You can DELETE * the entries from the table for the selected product and then INSERT the new values

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