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 "
" . $row['user_id'] . "--". $row['fname']. "";
}
foreach ($res as $row) {
echo "
" . $row['user_id'] . "--". $row['fname']. "";
}
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.