繁体   English   中英

PHP:如何使已保存在表中的值显示为被检查?

[英]Php : How can I make values that have been saved in a table appear on the page as being checked?

我的应用程序中有一个表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>

所以看起来像这样:

图片。

如果选中其中一个框然后保存,则该联系人将保存到如下的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();
?> 

但是无论何时回到页面,我仍然会看到:

在此处输入图片说明

如何显示来自contacts表的联系人,这些contacts也位于review_shared表中,并在相应的复选框中打勾?

首先从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 }}?>

暂无
暂无

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

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