我有3张桌子:
people:
------------------------
peopleID,
firstname
peopletype:
------------------------
peopletypeID,
type
peoplepeopletype (junction table):
------------------------
peopleID,
peopletypeID
在添加表单上一切都很好,但是我有问题显示已为指定的人员类型检查的复选框
这是我的代码。
从peoplepeopletype表中检索数据:
/*PEOPLE TYPE ************* */
$stmt = $conn->prepare("SELECT * FROM peoplepeopletype WHERE peopleID=?");
// set parameters and execute
if ( !$stmt ) { echo "error"; }
else if ( !$stmt->bind_param('i', $_GET['peopleID']) ) { echo "error";}
else if ( !$stmt->execute() ) { echo "error"; }
else {
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$peopletypeIDfromdb = $row ['peopletypeID'];
echo $peopletypeIDfromdb; /*echo only for test purposes, but I don't know how to use this in the form */
}
} /* end else */
显示复选框:
<?php /*retrieve peopletype from db */
$sql = "SELECT * from peopletype";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo '<input required="required" type="checkbox" name="peopletypeID[]" value="' . $row["peopletypeID"] . '"';
if ($peopletypeIDfromdb = $row["peopletypeID"]) { /*problem is probably here*/
echo 'checked';
}
echo '>' . $row["type"];
}
?>
感谢您的帮助!
答案 0 :(得分:0)
如果您可以将多个类型附加到一个人,则您需要更改第一个循环以将所有类型存储在一个数组中。我将它们存储为密钥,以便在分配给该人的类型中检查将来某种类型存在的最低复杂性。
$result = $stmt->get_result();
$types = array();
while($row = $result->fetch_assoc()) {
$types[$row ['peopletypeID']] = 1;
}
然后在第二个循环中使用它:
while($row = $result->fetch_assoc()) {
echo '<input required="required" type="checkbox" name="peopletypeID[]" value="' .
$row["peopletypeID"] . '" ';
if(isset($types[$row["peopletypeID"]]))
{
echo 'checked';
}
echo '>' . $row["type"];
}