Tuesday, February 22, 2022

[FIXED] Why does PDO fetch() return only the first row?

Issue

When I select and print it, it shows only the first row, the query is the same. Why does it return only one row?

PHP Code:

$e = $db->query("SELECT `username`, `membership` FROM `users` WHERE `expire` != ''")->fetch();
print_r($e);

Result with PHP:

Array ( [username] => ItzBruney05 [0] => ItzBruney05 [membership] => 300 [1] => 300 ) 

Result when query is executed in phpMyAdmin:

enter image description here


Solution

To select all rows using PDO, you need to use fetchAll() instead of fetch().

$e = $db->query("SELECT `username`, `membership` FROM `users` WHERE `expire` != ''")->fetchAll();

In PDO, fetch() returns "the next row from a result set".

fetchAll() returns "an array containing all of the result set rows".



Answered By - GrumpyCrouton

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.