我在数据库中有两个表名为groups( groupID,groupName )和userBelongToGroups( userID,groupID )。
groups userBelongToGroups
=================== =====================
groupID | groupName userID | groupID
------------------- ---------------------
1 | A 1 | 1
2 | B 1 | 2
3 | C 2 | 2
4 | D 3 | 1
3 | 3
4 | 4
我想在下拉菜单中显示当前用户的列 groupName 的所有值。
<select class="form-control" id="system_tags" name="system_tags">
<?php
$userID = $_SESSION['userID'];
// select the values from 'groupName' column
$sql = "SELECT groupName FROM groups, userBelongToGroups WHERE userID = '$userID' and `groups.groupID = userBelongToGroups.groupID`";
$result = mysqli_query($connection, $sql);
// display the values from 'groupName' table column
while ($row = mysqli_fetch_array($result)){
echo "<option value='".$row['groupName']."'>".$row['groupName']."</option>";
} ?>
</select>
所以当&#39; $ userID&#39; = 1,它应该在下拉菜单中显示两个选项A和B.
注意:SQL查询在MySQL中运行完美。
SELECT groupName FROM groups, userBelongToGroups WHERE userID = '1' and groups.groupID = userBelongToGroups.groupID
答案 0 :(得分:0)
应该阅读
WHERE userID = '$userID' and groups.groupID = userBelongToGroups.groupID";
如果没有设置默认值,也会尝试从会话中设置$ userID。因此,您应该拥有类似的内容,而不是$userID = $_SESSION['userID']
。
$userID = 0;
if(isset($_SESSION['userID'])){$userID = $_SESSION['userID'];}
最后,您可以考虑在此类查询中使用JOIN
,例如:
SELECT a.groupName FROM groups a JOIN userBelongToGroups b ON a.groupID = b.groupID AND b.userID = '$userID';