Good day. I don’t really understand why I can use fetchAll() only 1 time? The second time, an empty array is returned.

 $statement = $pdo->query($someSql); $a = $statement->fetchAll(); $b = $statement->fetchAll(); // empty array 

Why it happens? After all, as I correctly understand, the result of the query (result set) is stored in $statement after the query() ? What prevents to get it again?

    3 answers 3

    According to the documentation :

    PDOStatement :: fetchAll () returns an array containing all the remaining rows in the result set.

    Pay attention to the word "remaining" and think:
    You have completed the first fetchAll , it returned all the records in the set. What is left?
    Nothing, empty.
    That's it, and it will return the second fetchAll .

      Because PDO fetchAll selects the remaining records. Consequently, after the first pass of such records does not remain. In order to re-select the data using this method, you must return the current position of the cursor to the beginning of the record. By default, the cursor opens in forward-only mode PDO::CURSOR_FWDONLY .

      You can change this behavior by setting the cursor to PDO::CURSOR_SCROLL .

       $db->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL)); 

      However, it should be borne in mind that, until recently, MySQL did not support cursors and an attempt to crank the like on it would end in failure. Therefore, it is safer to keep records in the intermediate storage or repeat the request after closing the $statement->closeCursor() cursor.

        Because this code does not make the slightest sense.

        Having received the array once, you can use it as you like, without recourse to the layer for working with the database.