user1895377
user1895377

Reputation: 201

PDO - using same query for multiple foreach loops

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>';
}
}

Upvotes: 1

Views: 1115

Answers (1)

Hazem Mohamed
Hazem Mohamed

Reputation: 564

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.

Upvotes: 1

Related Questions