2010-10-21 83 views
2

我有從數據庫中顯示的數據有點問題......顯示數據從多個MySQL表

我有兩個數據庫表:

  • 類別(CAT_ID,cat_name)
  • menu_items (menu_id,MENU_NAME,CAT_ID,menu_description,menu_price)

我想d isplay數據爲:

Categorie 1名稱

  • CAT_ID = 1,MENU_NAME,menu_description,menu_price
  • CAT_ID = 1,MENU_NAME,menu_description,menu_price
  • CAT_ID = 1,...

Categorie 2名

  • CAT_ID = 2,MENU_NAME,menu_description,menu_price
  • CAT_ID = 2,MENU_NAME,menu_description,menu_price
  • CAT_ID = 2,...

Categorie 3名稱

  • cat_id = 3,menu_name,menu_description,menu_price
  • cat_id = 3 ,MENU_NAME,menu_description,menu_price
  • CAT_ID = 3,....

...


我的代碼:

function get_menu_items() { 
     // query database for a list of categories 
     $conn = db_connect(); 
     $query = "select cat_id, cat_name from categories"; 
     $result = @$conn->query($query); 
     if (!$result) { 
     return false; 
     } 
     $num_cats = @$result->num_rows; 
     if ($num_cats == 0) { 
      return false; 
     } 
     $result = db_result_to_array($result); 
     return $result; 
    } 


function display_menu_items($menu_array) { 
    if (!is_array($menu_array)) { 
    echo "<p>No menu items currently available</p>"; 
    return; 
    } 
    foreach ($menu_array as $row) { 
    echo "<section id='".$row['cat_name']."'>"; 
    echo "<div class='group course'>"; 
    echo "<h3>".$row['cat_name']."</h3>"; 

    ***/* Problem */*** 

    echo "<ul>"; 
foreach... { 
    echo "<li>cat_id = #, menu_name, menu_description, menu_price</li>"; 
    } 
    echo "</ul> 

    ***/* Problem */*** 

    echo "</div>"; 
    echo "</section>"; 
    } 
} 

有什麼建議?

謝謝。

回答

2
catRecordset = select * from categories 
foreach cat in catRecordset 
{ 
    print(cat.name); 
    menuRecordset = select * from menu where menyu.cat_id = cat.cat_id 
    foreach(menuItem in menuRecordSet) 
    { 
     print(menuItem.whatever); 
    } 
} 
0

甚至更​​好地利用加入,只運行一個查詢

$Recordset = 'select * from categories cat LEFT JOIN menu ON menu.cat_id = cat.cat_id'; 

$category = ''; 
foreach $record in $Recordset 
{ 
    if ($category != $record['cat_id']) { 
     print(cat.name); 
     $category = $record['cat_id']; 
    } 
    print($record['menu_name'] .....); 
}