0

这是我用来从 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 'CourseTitle'

/* 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)) {

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

4

2 回答 2

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>";
}

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

于 2012-04-04T18:49:38.227 回答
0

添加:

GROUP BY c.title

到您的 SQL 语句的末尾。

于 2012-04-04T18:20:34.563 回答