2013-10-10 106 views
0

我有這樣的代碼:while()循環的結果太多

$atrr_row = mysql_query("SELECT * FROM " . DB_PREFIX . "product_attribute WHERE product_id='".$r['product_id']."' and language_id=1"); 
while($atr=mysql_fetch_array($atrr_row)){ 
    $attr_n_g = mysql_fetch_array(mysql_query("SELECT name FROM " . DB_PREFIX . "attribute_description WHERE attribute_id = '" . $atr['attribute_id'] . "' and language_id=1 LIMIT 1")); 
    $attr_t.="\t".'<spec name="'.$attr_n_g['name'].'"><![CDATA['.$atr['text'].']]></spec>'."\n"; 
} 

應該從2個表得出的結果,但它給normaly首創產品信息,然後X2用於其他產品和以此類推,直到所有的產品都循環和結果是乘以x375。

Looped data: 
First product: 
<specs> 
<spec name="Age rating"> 
<![CDATA[18+]]> 
</spec> 
<spec name="Release date"> 
<![CDATA[2012]]> 
</spec> 
<spec name="Online mode"> 
<![CDATA[No]]> 
</spec> 
<spec name="Metacritic score"> 
<![CDATA[75 - 89]]> 
</spec> 
</specs> 

Second product: 
<specs> 
<spec name="Age rating"> 
<![CDATA[18+]]> 
</spec> 
<spec name="Release date"> 
<![CDATA[2012]]> 
</spec> 
<spec name="Online mode"> 
<![CDATA[No]]> 
</spec> 
<spec name="Metacritic score"> 
<![CDATA[75 - 89]]> 
</spec> 
<spec name="Age rating"> 
<![CDATA[16+]]> 
</spec> 
<spec name="Release date"> 
<![CDATA[2011]]> 
</spec> 
<spec name="Online mode"> 
<![CDATA[Yes]]> 
</spec> 
<spec name="Metacritic score"> 
<![CDATA[90 - 100]]> 
</spec> 
</specs> 

等等......任何想法?

編輯

product_attribute表: http://i.imgur.com/ROjBQT0.png

attribute_description表: http://i.imgur.com/6M5cNXi.png

+1

我不太清楚你想要做什麼,但我猜你的查詢中的JOIN會爲你節省很多工作,因爲你不必在循環中查詢你的數據庫。 – TheWolf

+0

請發表您的表格結構和所需輸出的例子。 – TheWolf

+0

缺少代碼,但它看起來好像只是在產品之間重置'$ attr_t'。你永遠追加它,所以每個產品的結果也都在它之後的所有產品上。 – Izkata

回答

0

我想你會更好的JOIN查詢,而不是像這樣循環。

"SELECT product_attribute.*, attribute_description.name FROM product_attribute LEFT JOIN product_description on product_description.attribute_id = product_attribute.id 
WHERE product_attribute.product_id='".$r['product_id']."'and language_id=1 
+0

這應該會爲您提供產品ID的所有產品屬性及其說明,您可以嘗試: 從product_attribute中選擇product_attrbute。*,其中product_attribute.product_id = –

0

你得到的一切兩次,因爲從數據庫中都與數字用繩子指標mysql_fetch_array返回值。使用mysql_fetch_assoc應該可以解決問題。