Although loops and multiple conditions

Is it possible to write several conditions in a while loop? If not, what is the alternative? I tried it and was returned with an error related to a line of code that sets the conditions for a while loop. Here is an example of what I mean.

$s = 1; while ($result_row = mysql_fetch_assoc($query) && $s < 5) { echo $result_row['id']; $s++; } 
+7
source share
4 answers

This is possible, but since = has a lower precedence than && , you need parentheses to make sure your statement is interpreted correctly:

 while (($result_row = mysql_fetch_assoc($query)) && ($s < 5)) 

The braces around $s < 5 are not required here, but I have included them for clarity.

However, it would be easier to just modify your query to return only 5 rows by adding LIMIT 5 .

 SELECT ... FROM yourtable ORDER BY ... LIMIT 5 
+22
source

You can try:

 $s=1 while ($result_row = mysql_fetch_assoc($query)) { echo $result_row['id']; $s++; if($s>5){ break; } } 

http://php.net/manual/en/control-structures.break.php

+1
source

while I see nothing wrong with that. on the contrary, to do something like this.

 $s = 1; while ($result_row = mysql_fetch_assoc($query)) { if($s < 5) { //enter the condition } $s++; } 
0
source

The value of $result_row is probably set to the logical condition of whether mysql_fetch_assoc($query) returns something true-ish and $s less than 5. Therefore, trying to read $result_row as a dictionary no longer works.

You can use parentheses to pinpoint how things are sorted:

 while (($result_row = mysql_fetch_assoc($query)) && ($s < 5)) 

So $result_row gets the mysql_fetch_assoc($query) value that you need, and the loop continues until the boolean value of this assignment returns something true, and also s less than 5.

0
source

All Articles