1

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>';
}
}
2
  • Define not work. Have you check var_dump($champs); before your second loop. Are you using $champs after first & before second loop anywhere ? Commented Jan 17, 2014 at 4:50
  • @Rikesh not work as in no results show up when it should be the same results as the first loop. And no, $champs is not used anywhere else in the code. Also, var_dump shows object(PDOStatement)#2 (1) { ["queryString"]=> string(51) "SELECT * FROM champs WHERE middle = '1' ORDER BY id" } Commented Jan 17, 2014 at 4:51

1 Answer 1

1

Try this

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

This will convert your results to an array which you can use as you like. Also you must check for isset($champs) or !empty($champs) before using it.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.