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

php: using for loop in function to display data from db

Hi! My program below is called using "echo get_all_books_info(); " in the index page. It displays the first row in the database but not the rest. It seems that there is something wrong with my for loop:

function get_all_books_info(){
require_once('connect.php');
$query = "SELECT * FROM book";
$result = mysql_query($query);

if(!$result) die("Oh crap...: " . mysql_error());

$rows = mysql_num_rows($result);

for ($j = 0 ; $j <= $rows; $j++)
{
    $return = "";   
    $row = mysql_fetch_row($result);
    $return = '<ul class="books">';
    $return = $return . "<li><h2>" . $row[1] . "</h2>" . " (". $row[5] .       ")" . "</li>";
    $return = $return . "<li>" . $row[2] . "</li>";
    $return = $return . "<li>" . $row[3] . "</li>";
    $return = $return . "<br/>";
    $return = $return . "<li>" . $row[4] . "</li>";
    $return = $return . "</ul>";
    return $return;
}

}

The program does return one row, but it seems that it never returns back to the loop so the $row variable can be set to the next row in the db by the php function mysql_fetch_row as this have a built in counter.

Can anyone help me with this please?

1 Answer

From the PHP Documentation:

"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. "

PHP is not my strongest area but I think this may help:

function get_all_books_info() {

    require_once('connect.php');
    $query = "SELECT * FROM book";
    $result = mysql_query($query) or die("Oh crap...: " . mysql_error());

    while($row = mysql_fetch_assoc($result)) {
        $return = '<ul class="books">';
        $return .= "<li><h2>" . $row[1] . "</h2>" . " (". $row[5] .")" . "</li>";
        $return .= "<li>" . $row[2] . "</li>";
        $return .= "<li>" . $row[3] . "</li>";
        $return .= "<br/>"; 
        $return .= "<li>" . $row[4] . "</li>";
        $return .= "</ul>";
        echo $return;
    }
}

Then to call the function just use

get_all_books_info();