我正在尝试填充数据库中两个不同表的下拉列表,它们使用前两个中的ID在第3个表中连接在一起。我使用第一个答案here作为下拉菜单的指南。
表格: 课程 - 身份证,头衔; 类 - id,title; classes_to_courses - coursesID,classesID
代码:
<?php
include("global.php");
doHeader();
$currentCourseClass = "SELECT id, title FROM courses";
$rsCurrentCourseClass = mysql_query($currentCourseClass);
while($get_row = mysql_fetch_assoc($rsCurrentCourseClass)) {
$categories[] = array("id" => $get_row['id'], "val" => $get_row['title']);
}
$currentCourseClass2 = "SELECT cl.id as classid, cl.title as classtitle, cr.id as courseid FROM classes_to_courses c2c LEFT JOIN classes cl ON c2c.coursesID = cl.id LEFT JOIN courses cr ON c2c.classesID = cr.id";
$rsCurrentCourseClass2 = mysql_query($currentCourseClass2);
while($get_row = mysql_fetch_assoc($rsCurrentCourseClass2)) {
$subcats[$get_row['courseid']][] = array("id" => $get_row['classid'], "val" => $get_row['classtitle']);
}
/**/
$jsonCats = json_encode($categories);
$jsonSubCats = json_encode($subcats);
?>
我的问题似乎是第二个查询$ currentCourseClass2。如何从已连接的表classes_to_courses中选择courseid,以便正确设置我的数组?
感谢。
答案 0 :(得分:0)
不确定您收到了什么错误,但看起来您的加入可能有误。在代码段中,您有:
SELECT
cl.id as classid,
cl.title as classtitle
cr.id as courseid
FROM classes_to_courses c2c
LEFT JOIN classes cl ON c2c.coursesID = cl.id
LEFT JOIN courses cr ON c2c.classesID = cr.id";
因此,您尝试使用c2c.coursesID加入classes表,反之亦然,以获取课程表。
相反,你不应该根据c2c.classesID和c2c.coursesID上的courses表加入classes表吗?
SELECT
cl.id as classid,
cl.title as classtitle
cr.id as courseid
FROM classes_to_courses c2c
LEFT JOIN classes cl ON c2c.classesID = cl.id
LEFT JOIN courses cr ON c2c.coursesID = cr.id";