Why can't I loop over $q->fetch() twice?

后端 未结 2 931
北恋
北恋 2021-01-20 14:50

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

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-20 15:19

    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.

    • PHP.net on PDOStatement::fetchAll()

提交回复
热议问题