我的数据库中有如下名称......
使用下面的代码,我在页面上看到这些用户,旁边有一个复选框。
$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)) {
echo "<input type='checkbox' name='check_contacts[]' >" . $row['username'] . "<br>";
if(!empty($_POST['check_contacts'])) {
foreach($_POST['check_contacts'] as $check) {
echo $check; //echoes the value set in the HTML form for each checked checkbox.
//so, if I were to check 1, 3, and 5 it would echo value 1, value 3, value 5.
//in your case, it would echo whatever $row['Report ID'] is equivalent to.
}
}
}
$con->close();
如果选中复选框,我怎么能这样做?如果检查了这些名字,结果将像Will Shakespeare John Grisham
一样回显?我想在input type
部分我会简单地提出
value=" $row['username'] "
但它不起作用。
答案 0 :(得分:1)
您希望将表单回显如下:
echo "<label><input type='checkbox' name='check_contacts[]' value='". $row['contact_id'] ."'>". $row['username'] ."</label>";
验证时我建议先isset()
使用!empty()
:
if(isset($_POST['check_contacts']) && !empty($_POST['check_contacts'])){
foreach($_POST['check_contacts'] as $value){
echo $value;
}
}
如果索引不存在,则不会以这种方式提示警告。
如果在提交表单时没有选中复选框,则数组将为空并且不显示任何值。
最好将id用作值,因为您始终可以使用它们查询数据库。
答案 1 :(得分:0)
此代码适用于我:
//this code below will get the username of contacts
// for $user_id
$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);
?>
<form action="" method="post">
<?php
//show the usernames, phone numbers
while($row = mysqli_fetch_assoc($result2)) { ?>
<input type='checkbox' name='check_contacts[]' value='<?=$row['username']?>'> <?php echo $row['contact_id'] ?> </br>
<?php
//we need the php bracket below to close the while loop
}
?>
<input type="submit" />
</form>
<?php
if(!empty($_POST['check_contacts'])) {
foreach($_POST['check_contacts'] as $check) {
echo $check; //echoes the value set in the HTML form for each checked checkbox.
//so, if I were to check 1, 3, and 5 it would echo value 1, value 3, value 5.
//in your case, it would echo whatever $row['Report ID'] is equivalent to.
}
}
$con->close();
?>