Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No condition in PHP while loop?

So, I'm building my first super basic CMS using PHP. I don't want to simply copy the code from the tutorial I'm watching, but really understand it. One thing that bothers me is the use of the while loop for fetching posts. In the code below, I can't see how the statement inside within the rounded brackets constitute a condition. Seems to me all it does is assigning an array to the variable $post. How can you loop over something that is not a condition is my question, I suppose. Thanks!

function get_posts () {
   $query = mysql_query("SELECT * FROM posts") or die(mysql_error());

   while ($post = mysql_fetch_assoc($query)) {
      echo $post['Content'];
   }
}

2 Answers

STOP!

The tutorial you're watching is severely outdated! Please, don't use mysql_* functions in new code. They are no longer maintained and the deprecation process has begun on it. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.


As for the specific question, this line

while ($post = mysql_fetch_assoc($query)) {

Is the condition. mysql_fetch_assoc() returns an array if there are more results, and false, in the case there aren't any. If it returns false, the condition will evaluate to false and the loop would break.

like image 82
Madara's Ghost Avatar answered Sep 03 '26 13:09

Madara's Ghost


Basicaly you are fetching new row and assigning it to $post variable with:

while ($post = mysql_fetch_assoc($query))

mysql_fetch_assoc:

Return Values

Returns an associative array of strings that corresponds to the fetched row, or FALSE if there are no more rows.

So when mysql_fetch_assoc returns false it is assigned to $post variable and then it is evaluated within while, then loop stops.

like image 24
Zbigniew Avatar answered Sep 03 '26 14:09

Zbigniew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!