简体   繁体   English

CheckBox和数据库更新

[英]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. 每个复选框都有一个领子ID,将在提交表单时提交。

领型

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. 然后我做的是使用insert语句将这三个项圈添加到我的项圈表。 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? 我是否必须为每个复选框编写SELECT语句,并查看该项ID是否存在?

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? 我是否必须为每个复选框编写SELECT语句,并查看该项ID是否存在?

The database can tell you if that ID exists or not, so that does the database. 数据库可以告诉您该ID是否存在,因此数据库也是如此。

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. 我想如果您可以为特定用户保存id或product_id,而不是删除其早期条目,并使用该ID创建该用户的新行。 Or Update that row using the id. 或者使用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: 您必须从表中选择所有ID并验证是否选中了复选框:

     $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 您可以从表中删除所选产品的条目,然后插入新值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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