Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Array Only Returning 1 Result from PHP Method

When I put this query in a PHP method I am only getting one result from the array. Please help.

<?php


class Art
{

    public function __construct(){
    $mysqli = $this->mysqli = new mysqli("localhost", "root", "Password1", "foliodb0");
    }

public function getUrl() { 
$result= $this->mysqli->query("SELECT art_url FROM art_info LIMIT 4");

    if($result === FALSE) {
       die(mysqli_error()); 
}
    if ($result->num_rows > 0 )  {
        while($row = mysqli_fetch_array($result))
             {
           $rows[] = $row;

        }

            foreach ($rows as $row)
             {
           return  print_r($row['art_url']);    
        }
    }
        else  {
            echo "0 results";
        }   

}
public function __destruct(){
    $this->mysqli->close();
    }

}

$url = new Art();
echo $url->getUrl();

?>

I edited it your post to show the code correctly. Try to use Markdown syntax when posting your code please.

1 Answer

PHP is not my strongest area but couldn't you simplify this to:

<?php
if(!$result) {
    die(mysqli_error()); 
}

if($result) {
    while($row = mysqli_fetch_array($result))
    {
        echo $row['art_url'];
    }
} else {
    echo "0 results";
} 
?>

Also, it's important to note:

"If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call."

From the PHP documentation.

That did it! Thanks so much!

Glad it worked for you!