Assume I\'m in need to loop twice with the result I got form PDO prepared statement.
First loop works fine, the next one does not work
The value of var_d
When you loop the row, you empty out the result set. If you want to loop over multiple times, you can use fetchAll()
, store that in a variable and loop that where you need using a foreach
loop.
$q = $dbconnection->prepare("SELECT * from users WHERE role=?");
$q->execute(array($id)); //Boolean true or false
$res = $q->fetchAll();
foreach ($res as $row) {
echo "<br/>" . $row['user_id'] . "--". $row['fname']. "</br>";
}
foreach ($res as $row) {
echo "<br/>" . $row['user_id'] . "--". $row['fname']. "</br>";
}
Alternatively, you can execute the query again, but if you do that, you make a double query to the database. So you query twice for the same data, which isn't very efficient.
Also you had execute(array('$id'))
, which would be the exact string $id
, and not the variable representation. See the PHP manual on strings. So it should be execute(array($id))
instead.
Your are fecth a row time by time if you need two iteration you should perform a copy eg storing rows
while ($row = $q->fetch(PDO::FETCH_ASSOC)){
echo "<br/>" . $row['user_id'] . "--". $row['fname']. "</br>";
$my_rows[] = $row;
}
// second loop this loop will NOT echo any thing ?!
foreach($my_rows as $key=>$value){
echo "<br/>" . $value['user_id'] . "--". $value['fname']. "</br>";
}