我有两个表,employee
作为父级,license
作为子级。它们都有一个Lic_ID
列供参考,此列是PK
中的license
和FK
中的employee
。 license
表还有一列Lic_Type
,其中包含许可证的名称。
我正在尝试创建一个包含列表框的表,以便可以更新employee
表。列表框value
需要填充license.Lic_ID
,license.Lic_Type
将显示在option
中。这就是我所拥有的:
(Employee name, Id, etc. called out up here)
<?php
echo "<select name=\"Lic\">";
echo "<option value=\"\">Select...</option>";
$sql = $mysqli->query("SELECT Lic_ID, Lic_Type FROM license");
while($row = $result->fetch_assoc())
{
echo "<option value=\"" . $row['Lic_ID'] . "\">" . $row['Lic_Type'] . "</option>";
}
echo "</select>";
?>
因此效果很好,它显示许可证类型并将值设置为许可证ID。如果为员工设置了许可证ID,我想要做的是<option selected="selected">
。这段代码不起作用,但我认为它说明了我正在尝试做的事情:
<?php
echo "<select name=\"Lic\">";
echo "<option value=\"\">Select...</option>";
$sql = $mysqli->query("SELECT license.Lic_ID, license.Lic_Type, employee.Lic_ID FROM employee INNER JOIN license ON employee.Lic_ID = license.Lic_ID");
while($row = $result->fetch_assoc())
{
echo "<option value=\"" . $row['license.Lic_ID'] . "\"";
if($row['employee.Lic_ID'] = $row['license.Lic_ID']){echo "selected=\"selected\";}
echo ">" . $row['license.Lic_Type'] . "</option>";
}
echo "</select>";
?>
有没有办法完成我想要做的事情?
答案 0 :(得分:1)
我认为对于我究竟想要完成的事情可能存在一些困惑,我为不太清楚而道歉。无论如何,我今天偶然发现了答案,所以我想我应该发布它。
$sql1 = ("SELECT Emp_Name, Lic_MAT_ID FROM employee");
if(!$result_employee_query = $mysqli->query($sql1))
{
die ("There was an error getting the records from the employee table");
}
while($employee = $result_employee_query->fetch_assoc())
{
echo "Employee Name: " . $employee['Emp_Name'] . "<br>";
echo "License: ";
echo "<select>";
$sql2 = ("SELECT Lic_MAT_ID, Lic_MAT_Type FROM license_mat");
if(!$result_license_query = $mysqli->query($sql2))
{
die ("There was an error getting the records from the license table");
}
while($license = $result_license_query->fetch_assoc())
{
echo "<option value=\"" . $license ['Lic_MAT_ID'] . "\"";
if($license['Lic_MAT_ID'] == $employee['Lic_MAT_ID'])
{
echo " selected=\"selected\"";
}
echo ">" . $license ['Lic_MAT_Type'] . "</option>";
}
echo "</select><br>";
}
答案 1 :(得分:0)
我理解您的问题:您想查看许可证是否已添加到任何用户或是否已取消分配。如果任何用户拥有许可证集,那么它将被“选中”,而其他用户则不会。
首先,您必须将关键字"multiple"
分配给select
对象,使其成为列表框:
echo "<select name=\"Lic\" multiple=\"multiple\">";
第二:我会写这种查询:
$sql = $mysqli->query("SELECT l.Lic_ID, l.Lic_Type, e.cnt FROM licence l left outer join (select Lic_id, count(*) cnt from employee group by Lic_id) e on l.Lic_ID=e.Lic_id");
选择Lic_ID
,Lic_Type
和count
,其中有多少员工设置了相应的Lic_ID(left outer join
)
并在代码中检查,如果count
高于0
if($row['cnt'] > 0){
echo "selected=\"selected\";
}