2012-04-04 28 views
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; 

這裏取mysql的結果的屏幕截圖,我的結果取 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)) { 

請指引我建立一個正確的和更好的代碼

+1

如果您的設計需要將表格/字段名稱存儲在其他字段中,則應重新設計您的設計。它會很快變成不可維護的混亂。 – 2012-04-04 18:14:18

回答

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

上面的代碼只打印出第一兩列 ,但如果你能得到它的工作,你應該能夠很容易地添加其餘部分。

+0

頁面結果爲空:( – Amanullah 2012-04-04 19:00:53

+0

嘗試添加一些調試行 - 在while循環結束時,您可以把:echo「添加一行。「 – Annabel 2012-04-04 19:32:10

+0

while循環後放'print_r($ courses);'。然後使用視圖源來看看會出現什麼。也許問題是你的查詢不起作用。 – Annabel 2012-04-04 19:35:45

0

add:

GROUP BY c.title 

到您的SQL語句的末尾。

+0

我將管理SQL查詢只是告訴我如何可以得到foreach的html表格作爲foreach列名稱 – Amanullah 2012-04-04 18:39:41