I have two foreach loops in my code that use the same query, so I was wondering if I could just make the query at the beginning of the page and just call it later in the code so I only have to access the database once. I tried this and the first loop went through but the second one did not. Is there a way to only query once but use it in two foreach loops? This is what I thought might be the answer:
$sql = "SELECT * FROM champs WHERE $role = '1' ORDER BY id";
if (!empty($role)) {
$champs = $db->query($sql);
}
Some 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>';
}
}
Some more 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>';
}
}
var_dump($champs);before your second loop. Are you using$champsafter first & before second loop anywhere ?$champsis not used anywhere else in the code. Also,var_dumpshowsobject(PDOStatement)#2 (1) { ["queryString"]=> string(51) "SELECT * FROM champs WHERE middle = '1' ORDER BY id" }