在foreach()循环中优化SQL查询

时间:2015-08-07 11:36:13

标签: php mysql

如果不将查询放在foreach循环中,我还能如何获得name

PHP:

$material_decode=json_decode($materials['materials']);
foreach($material_decode as $material_id=>$material_value)
{
    $forge_materials=mysql_fetch_assoc(mysql_query('SELECT `name` FROM `forging_materials` WHERE `id`='.$material_id.' LIMIT 1'));
    echo '<tr>'.
        '<td>'.
            $forge_materials['name'].
        '</td>'.
        '<td>'.
            number_format($material_value).
        '</td>'.
    '</tr>';
}

$ material_decode(forge_material_id =&gt; material_value):

stdClass Object
(
    [2] => 25
    [4] => 32
    [5] => 23
)

3 个答案:

答案 0 :(得分:2)

您可以使用循环外的 WHERE IN 一次性获取所有需要的记录。 这种方式只需要单个查询

这对你有用:

$material_decode = json_decode($materials['materials'], true);
$forge_materials = mysql_query('SELECT `id`, `name` FROM `forging_materials` WHERE `id` IN ( '. implode(',', array_keys($material_decode)) .')');

while($row = mysql_fetch_assoc($forge_materials))
{
    echo '<tr>'.
      '<td>'.
        $row['name'].
      '</td>'.
      '<td>'.
        number_format($material_decode[$row['id']]).
      '</td>'.
    '</tr>';
}

请注意, mysql _ 方法已被弃用,现在建议使用 PDO mysqli _ 方法。您可以在文档中阅读更多内容:

答案 1 :(得分:0)

首先运行SELECT id,name FROM forging_materials WHERE 1它将获取所有ID&amp;表中的名称,然后在foreach循环中,从查询结果中获取id等于$material_id的名称

答案 2 :(得分:0)

更新了您的代码。试试这个

$forge_materials_name   =   "";

$material_decode=json_decode($materials['materials']);
foreach($material_decode as $material_id=>$material_value)
{
    if( empty($forge_materials_name) )
    {
        $forge_materials=mysql_fetch_assoc(mysql_query('SELECT `name` FROM `forging_materials` WHERE `id`='.$material_id.' LIMIT 1'));  
        $forge_materials_name   =   $forge_materials['name'];
    }
    echo '<tr>'.
        '<td>'.
            $forge_materials_name.
        '</td>'.
        '<td>'.
            number_format($material_value).
        '</td>'.
    '</tr>';
}