0

I wrote a function that should return all users in the database. It's printing the array, but it's only printing one result. Why is it doing this? I surrounded it in a while loop and put a limit in my query...

Code:

function getAllUsers() {

global $PDO;

    $stm = $PDO->prepare("SELECT * FROM `users` ORDER BY `bid` DESC LIMIT 15");

        $stm->execute();

            while($Array = $stm->fetch()) {
                return print_r($Array);
            }

}
2
  • 1
    using return in a loop will only result to one result. Commented Oct 2, 2013 at 3:11
  • You can wait and look at the answers below, or do yourself a favor and learn some basics on certain channels like here Commented Oct 2, 2013 at 3:16

3 Answers 3

3

Use fetchAll() :

$data = $stm->fetchAll()
foreach ($data as $item ) {
    print_r($item);
}
Sign up to request clarification or add additional context in comments.

2 Comments

you can use the foreach loop instead of the while too
one hand washes the other @FouadFodail =)
1

use the foreach loop instead of the while and fetchAll() instead of the fetch():

foreach ($stm->fetchAll() as $arr) {
   print_r($arr);
}

1 Comment

dont use return, in loop it will only loop once
0
function getAllUsers() {

   global $PDO;

   $stm = $PDO->prepare("SELECT * FROM `users` ORDER BY `bid` DESC LIMIT 15");
   $stm->execute();

   $var = array();

   while($Array = $stm->fetch()) {

     $var = $Array;

  }

 return $var;

 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.