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

后端 未结 2 930
北恋
北恋 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 "<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.

    • PHP.net on PDOStatement::fetchAll()
    0 讨论(0)
  • 2021-01-20 15:31

    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>";
      }
    
    0 讨论(0)
提交回复
热议问题