加入MySQL表,然后将结果过滤为列名

时间:2012-04-04 18:08:58

标签: php mysql html

这是我用于从4个不同的表中获取mysql结果的代码

SELECT DISTINCT c.title as CourseTitle, t.title as TopicTitle, l.title as LessonTitle,    r.title as ResourceTitle, r.location, r.type, r.duration
FROM j17_lessons l, j17_topics t, j17_courses c, j17_resources r
WHERE
CONCAT(c.title, t.title, l.title, r.title, r.type, r.location) LIKE '%Fatih%'
AND c.id = t.course_id
AND l.topic_id = t.id
AND r.lesson_id = l.id
ORDER BY c.title, t.id, l.id, r.id;

以下是我的获取结果的屏幕截图 http://i40.tinypic.com/2v1w0ib.png

现在我需要为数据库中的每个“CourseTitle”创建一个HTML表格。

使用SQL语句和PHP代码我可以获得第一个查询的结果,但我需要第二个查询来分割表foreach'FourseTitle'

/* connect to the db */
$connection = mysql_connect('localhost','root','123');
mysql_select_db('alhudapk',$connection);

/* show tables */
$result = mysql_query('SELECT DISTINCT c.title as CourseTitle, t.title as TopicTitle,     l.title as LessonTitle, r.title as ResourceTitle, r.location, r.type, r.duration
FROM j17_lessons l, j17_topics t, j17_courses c, j17_resources r
WHERE
CONCAT(c.title, t.title, l.title, r.title, r.type, r.location) LIKE '%Taleem%'
AND c.id = t.course_id
AND l.topic_id = t.id
AND r.lesson_id = l.id
ORDER BY c.title, t.id, l.id, r.id',$connection) or die('cannot show tables');
while($tableName = mysql_fetch_row($result)) {

$table = $tableName[0];

echo '<h3>',$table,'</h3>';
$result2 = mysql_query('SELECT '.$table . 'AS' .$table);
if(mysql_num_rows($result2)) {

请指导我构建正确且更好的代码

2 个答案:

答案 0 :(得分:1)

我要做的是将数据库结果放入一个大型数组结构中,数据的排列顺序应与打印出来的顺序相同。这使得维护代码更容易。

// run the query as you did in the question

$courses = array();

// use mysql_fetch_assoc as it makes the code clearer
while($row = mysql_fetch_assoc($result)) {
    $ct = $row['CourseTitle'];
    // Found a new Course Title? If so create an array to put the data rows in
    if(!isset($courses[$ct]))
        $courses[$ct] = array();

    // add this row to the end of its course array
    $courses[$ct][] = $row;
}

// now print the results out
foreach($courses as $title =>$course) {
    echo "<h3>$title</h3>";
    echo "<table>";
    foreach($course as $line) {
        echo "<tr><td>" . $line['TopicTitle'] . "</td><td>" 
             . $line['LessonTitle'] . "</td></tr>";
    echo "</table>";
}

上面的代码只打印出前两列 ,但如果你可以让它工作,你应该能够很容易地添加其余部分。

答案 1 :(得分:0)

添加:

GROUP BY c.title

到SQL语句的末尾。