Php:如何将已保存在表格中的值显示在页面上作为选中状态?

时间:2017-02-25 09:35:44

标签: php mysql checkbox

我的应用中有一个表格contacts,其中用户(user_id)有一个联系人列表:

contact_auto_inc      user_id       contact_id
17                       2             7
18                       2             8
19                       2             9

我使用以下代码显示这些联系人及其相应的名称:

<form action="" method="POST">
    <?php
         //this code below will get the username of contacts
         // for $user_id. we get the 'contact_id'
         //values in the contacts table for $user_id, match those contact_ids to    the corresponding 
         //'user_ids' in the user table, and then show the 'usernames' for each of those user_ids
           $select_from_user_table = "SELECT  contacts.contact_id, user.username
         FROM contacts 
         INNER JOIN user
         ON contacts.contact_id=user.user_id WHERE contacts.user_id = '$user_id'";

        //get the result of the above
         $result2=mysqli_query($con,$select_from_user_table);

    //show the usernames, phone numbers
         while($row = mysqli_fetch_assoc($result2)) { ?>
         <input type='checkbox' name='check_contacts[]' value='<?=$row['contact_id']?>'> <?php echo $row['username'] ?> </br>

        <?php } ?>

    <!--<input type="submit" name = "create" value = "Create new Contact"></p> -->

    <!--</form> -->

<p><input type="submit" name = "Save" value = "Save"></p>
<p><input type="submit" name = "Delete" value = "Delete"></p>
<a href="exit.php">Exit</a>
</form>

所以它看起来像这样:

image.

如果其中一个框被选中然后保存,那么联系人就会保存到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) {

    $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();
?> 

但每当我回到页面时,我仍然会看到:

enter image description here

如何显示contacts表中同样位于review_shared表中的联系人 勾选相应的复选框?

1 个答案:

答案 0 :(得分:1)

首先从review_shared获取数据并在里面进行比较,如果匹配则检查否则取消选中:将checked="checked"添加到内部的复选框,同时检查它。

     <?php
      $review_shared=array(1,2,3,4);//get contact_id in this from shared table
     while($row = mysqli_fetch_assoc($result2)) {
        if(in_array($row['contact_id'],$review_shared)){ ?>
             <input type='checkbox' name='check_contacts[]' value='<?=$row['contact_id']?>' checked="checked"> <?php echo $row['username'] ?> </br>
         <?php  }else{?>
        <input type='checkbox' name='check_contacts[]' value='<?=$row['contact_id']?>' > <?php echo $row['username'] ?> </br>           
   <?php }}?>