2012-04-01 77 views
0

我有兩個表,一個包含頁/標題號碼和標題文本,另一個包含值每個標題下進行打印:組結果按標題從其他表

標題:

page | heading | text 
1 | 1  | "heading 1" 
1 | 2  | "heading 2" 

內容:

page | heading | contents 
1 | 1  | "some stuff" 
1 | 1  | "some more stuff" 
1 | 2  | "some other stuff" 

我想,如果第一頁的結果是:

heading 1 
some stuff 
some more stuff 
heading 2 
some other stuff 

在需要的地方添加HTML。

使用兩個while循環mysql_fetch_array()不起作用,因爲您必須先取得它,然後才能檢查它是否在正確的標題下。這意味着我錯過了每一個下一個標題的第一個輸入。

$query = "SELECT text,heading FROM headings WHERE page=".$page." ORDER BY heading ASC"; 
$headings = mysql_query($query) or die(mysql_error()); 
$query = "SELECT filename,heading FROM pictures WHERE page=".$page." ORDER BY heading ASC"; 
$pictures = mysql_query($query) or die(mysql_error()); 

while($heading = mysql_fetch_array($headings)){ 
echo $heading[0]; 
    while($image = mysql_fetch_array($pictures)){ # This skips entries because I have to check the contents themselves 
     if($image[1] != $heading[1]){ 
      break; 
     } 
     echo $image[0]; 
    } 
} 

有沒有辦法做到這一點,而不需要爲每個標題運行多個查詢? (頁面上可能有多個)

+0

查詢,似乎與直覺相反,意味着你有待辦事項在每個內容的每個查詢最少有一個連接 – 2012-04-01 13:21:12

+0

因爲每個標題有多個內容,所以我需要一個單獨的表格作爲標題。 – 2012-04-01 13:25:13

回答

1

只需在用while循環迭代之前將所有結果提取到2個數組中。

+0

'while($ images [] = mysql_fetch_array($ pictures)){}'?謝謝,這就像一個魅力 – 2012-04-01 13:27:00

1

您正在查找的是帶有JOIN的查詢。

我假定你的數據庫看起來是這樣的:Fiddle

包括的是,爲什麼你從它的內容分開的標題,你可能會尋找