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

Help I dont know why this code isnt working

When I do

var_dump(mysql_fetch_array($query));

It will bring back my array from the database but for some reason when the information goes through the while and then I echo it out there is nothing. I don't understand..

$all_responses = '';
$query = mysql_query("SELECT * FROM forum_post WHERE otid = '$thread_id' AND type = 'b'") or mysql_error();

$numRows = mysql_num_rows($query);

if($numRows < 1) {
    $all_responses = '<div class="alert alert-info text-center" role="alert">No one has respond to this post! You can be the first to post.<br></div>';

}

while ($rows = mysql_fetch_array($query)) {
    $reply_author = $row['post_author'];
    $reply_author_id = $row['post_author_id'];
    $date_n_time = $row['date_time'];
    $converted_time = ago($date_n_time);
    $reply_body = $row['post_body'];
    $all_responses .= '<li class="list-group-item">Re: ' . $thread_title . '&nbsp; &nbsp; &bull; <a href="#">' . $reply_author . '</a> said:' . $reply_body . '</li>';


}


?>

2 Answers

Watch out for using any of the php mysql functions to connect to the database. These were depreciated in version 5.5 and are pretty unsafe.

Instead you can use PDO (PHP data Object), which also protects you from MySQL injection.

PDO is used in Build a simple php application if you're interested in seeing how to include it :)

Darrius Taylor
Darrius Taylor
1,934 Points

I actually didn't know this. I haven't worked with PHP in some years. Is this information updated or detailed in the courses? I currently on the site to learn Android so I haven't delved into anything else yet.

I think all of the Treehouse courses encourage the use of PDO. This course is part of the Shirts4Mike project series, which should give you a nice introduction to PDO if you're interested. It does dive right into the middle of the project so you may want to start from scratch (see first post) or you could just download the project files.

Darrius Taylor
Darrius Taylor
1,934 Points

You named your array variable $rows and you are using $row[].

Change it to $rows[]

Update: Sorry, you should change: $rows = mysql_fetch_array($query) to $row = mysql_fetch_array($query)

The reason you wouldn't write it the other way around is because you are outputting a row every loop, not rows.