doumie6223 2012-10-22 06:13
浏览 38
已采纳

CheckBox和数据库更新

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.

collar types

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

collar types

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.

collar types

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

enter image description here

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

  • 写回答

3条回答 默认 最新

  • dplase3140 2012-10-22 06:25
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?