如何取消选中数据库中的值?

时间:2017-03-10 17:01:14

标签: php checkbox mysqli

使用我的代码,如果用户选中其中一个名称旁边的复选框 该名称将保存到我的review_shared表中。

enter image description here

我尝试使用我的代码,以便在取消选中某个框时,将从review_shared表中删除该名称。 你知道我怎么做,或者我应该从哪里开始?因此,如果取消选中Paul Thompson和/或Dan Frain,则会从review_shared表中删除它们。

    <?php
    //here we want to save the checked contacts to the review_shared table ;  that is,
    //who the user wants to share reviews with
    if(!empty($_POST['check_contacts'])) {
        foreach($_POST['check_contacts'] as $check) {

                    //$check="";
        //if the contact in review_shared is already checked, we don't want to save it multiple times
            $already_checked = "SELECT * from review_shared WHERE user_id = '$user_id' AND contact_id = '$check' AND review_id = " .$_GET['id'];

            $already_checked_result=mysqli_query($con,$already_checked);
            $num_rows = mysqli_num_rows($already_checked_result);

            if($num_rows >= 1) {
            echo "This is already a contact";
            }

        else if ($num_rows < 1) {

            //$_GET['id'] is the current review for which contacts are being edited, we are checking a contact to share that review with
                $insert_review_shared_command = "INSERT INTO review_shared VALUES(NULL," .$_GET['id']. ", '$user_id','$check')";

            //we want to save the checked contacts into the review_shared table
            $insert_into_review_shared_table = mysqli_query($con,$insert_review_shared_command);

        }

      }
   }

        $con->close();


        ?> 

2 个答案:

答案 0 :(得分:3)

实现您所需要的独特方式是

  • 删除所有条目
  • 插入选中的选项

保存表单数据时。

要删除所有以前的条目,请执行以下操作

$sql = "DELETE FROM review_shared WHERE your-conditions";

这是因为当您发布复选框时,您将只收到服务器端的已选中复选框。那些是您需要存储的数据。

答案 1 :(得分:0)

感谢上面的Simone Cabrino,我只是将其添加到我的代码中:

        $already_checked = "DELETE from review_shared WHERE user_id = '$user_id' AND review_id = " .$_GET['id'];
        mysqli_query($con,$already_checked);