2016-02-25 47 views
1

希望有人爲能幫助我 - 我有這樣的代碼:MySQL查詢 - 呼應組產品用foreach在風格化的div

$query = "SELECT * FROM `products` WHERE `category` = 100 AND `showme` = 1 `ORDER BY `nr` ASC";` 
$result = mysql_query($query); 
while($row = mysql_fetch_object($result)){ 
echo '<div class="'.$row->design.'"> 
    <img src="'.$row->img.'" width="100%"><br> 
    <span><b>'.$row->name.'</b></span><br><span>'.$row->descr.'</span><br /> 
    <span>'.$row->preprice.'&nbsp;</span><span>'.$row->price.'</span><span>&nbsp;'.$row->unit.'</span></div> 
'; 
} 

它顯示是這樣的:http://gartenundhof.de/gartenundhof-produkte5.php

它應該看起來大約像: http://gartenundhof.de/gartenundhof-produkte.php(其具有3個獨立的查詢)

+0

您按類別需要將它們分組。 ''''SELECT * FROM'products'WHERE'category'= 100 AND'showme'= 1 GROU_BY'category'ORDER BY'nr'ASC;''' 我很久沒做RAW RAW了,但是這個應該工作:/。 此外,而不是循環通過您的數據在第一個實例中,你也循環了類別。之後,爲每個類別顯示產品。 – Vlad

+0

對不起,我發送了錯誤的代碼: – velorider

回答

0
"SELECT * FROM 'products' ORDER BY 'category' ASC"; 

嘗試此

0

,您可以嘗試:

$query = "SELECT * FROM `products` WHERE `showme` = 1 `ORDER BY category,`nr` ASC"; 
$result = mysql_query($query); 
$category = -1; 
while($row = mysql_fetch_object($result)){ 
    if($category != $row->category) { 
     $category = $row->category; 
     eho "<h2>$category</h2>"; 
    } 
    echo '<div class="'.$row->design.'"> 
    <img src="'.$row->img.'" width="100%"><br> 
    <span><b>'.$row->name.'</b></span><br><span>'.$row->descr.'</span><br /> 
    <span>'.$row->preprice.'&nbsp;</span><span>'.$row->price.'</span><span>&nbsp;'.$row->unit.'</span></div>'; 
} 
0

假設你有2個表ProductsCategories

$categories_query = "SELECT * FROM categories ORDER BY id ASC"; 
$categories = mysql_query($categories_query); 

while($category = mysql_fetch_object($categories)) { 

    echo "Category: " . $category->name . "<br />"; 

    $products_query = "SELECT * FROM products WHERE category_id = " . $category->id . " AND showme = 1 ORDER BY nr ASC"; 

    while($product = mysql_fetch_object($products_query)) { 
    echo "Product: " . $product->name . "<br />"; 
    } 
}