PDO - 对多个foreach循环使用相同的查询

时间:2014-01-17 04:47:24

标签: php mysql pdo foreach

我的代码中有两个使用相同查询的foreach循环,所以我想知道我是否可以在页面的开头进行查询,稍后在代码中调用它,这样我只需要访问数据库一旦。我试过这个,第一个循环通过,但第二个循环没有。有没有办法只查询一次,但在两个foreach循环中使用它?这就是我认为可能的答案:

$sql = "SELECT * FROM champs WHERE $role = '1' ORDER BY id";
if (!empty($role)) {
$champs = $db->query($sql);
}

一些HTML

if (!empty($role)) {
foreach($champs as $row) {
     echo   '<div class = "champion_left">
     <p>'.$row['name'].'
      <img class = "face_left" src = "images/small/'.$row['name'].'.png">
      <div class = "name" onmouseover="if(champ1==\'\') preview1(\''.$row['name'].'\', \''.$row['name'].'\')" onmouseout="if(champ1==\'\')restoreAvatar1()" onClick="champ1 = \''.$row['name'].'\'; preview1(\''.$row['name'].'\', \''.$row['name'].'\')">
      </div>
     </p>
    </div>';
}
}

更多HTML

if (!empty($role)) {
foreach($champs as $row) {
     echo   '<div class = "champion_right">
     <p>'.$row['name'].'
      <img class = "face_right" src = "images/small/'.$row['name'].'.png">
      <div class = "name" onmouseover="if(champ2==\'\') preview2(\''.$row['name'].'\', \''.$row['name'].'\')" onmouseout="if(champ2==\'\')restoreAvatar2()" onClick="champ2 = \''.$row['name'].'\'; preview2(\''.$row['name'].'\', \''.$row['name'].'\')">
      </div>
      </p>
    </div>';
}
}

1 个答案:

答案 0 :(得分:1)

试试这个

    $sql = "SELECT * FROM champs WHERE $role = '1' ORDER BY id";
    if (!empty($role)) {
            $champs = $db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
    }

这会将您的结果转换为您可以随意使用的数组。另外,在使用之前,您必须先检查isset($champs)!empty($champs)