0

I'm having troubles with my function and how to retrieve the data. Here is what i got.

public function getImages()
{
    $array = array();

    //Test query
    $query = $this->connect()->query("SELECT * from user");
    while ($row = $query->fetch()) {
        $array[] = $row;
        return $array;
    }
}

Now I'm calling this function but i can not use foreach to access the array.

include "header.html";
include "autoload.php";
spl_autoload_register('my_autoloader');

$users = new User;
$users->getImages();

foreach ($users as $value) {
  echo $value["username"];
}

What am I doing wrong? I'm only getting one result but there are many in my database. Or if i call the $array in foreach it says undefined.

3
  • What is the code doing wrong? I assume you’re only getting one result. Look where your return statement is. And please always explain exactly what is wrong with the code so we don’t have to guess Commented Mar 3, 2019 at 13:01
  • You are right! I'm getting only one result. Commented Mar 3, 2019 at 13:02
  • I literally figured it out after I saw your comment! You are great! Thanks Commented Mar 3, 2019 at 13:06

2 Answers 2

1

A couple things. First, your function is only ever returning an array with one element in it. If you want to finish populating the array, don't return until after the loop:

while ($row = $query->fetch()) {
    $array[] = $row;
}
return $array;

And second, you're trying to iterate over the object which has the function, not the value returned from the function. Get the return value and iterate over that:

$userDAO = new User;
$users = $userDAO->getImages();

foreach ($users as $value) {
    echo $value["username"];
}
Sign up to request clarification or add additional context in comments.

Comments

1

You just need to put the return statement out of the while loop.

public function getImages() { 
      $array = array(); //Test query
      $query = $this->connect()->query("SELECT * from user"); 
       while ($row = $query->fetch()) { 
            $array[] = $row; 
        }
        return $array;
  }

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.