while()循环的结果太多了

时间:2013-10-10 19:23:11

标签: php mysql while-loop

我有这段代码:

    $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个表的结果,但它给出了正常的第一个产品信息,然后是另一个产品的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

2 个答案:

答案 0 :(得分:0)

你得到的东西都是两次,因为mysql_fetch_array会使用数字和字符串索引从数据库中返回值。使用mysql_fetch_assoc可以解决问题。

答案 1 :(得分: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
相关问题