Page 1 of 1

Second condition causes first cobdition to fail

Posted: Wed Dec 24, 2003 6:12 pm
by Bill H
(Had a little trouble coming up with a meaningful title for this post.) Anyway, consider the following code:

Code: Select all

<?php
$Query = "SELECT * FROM Reports WHERE Assn=40 AND (Date>'$Sdate' OR Stat=0)";
$Result = mysql_query($Query, $Link);
$Cntr = 0;                          // we are just printing the first eight stores

while ($Row = mysql_fetch_array($Result) && $Cntr < 
{    $Query = "SELECT * FROM Stores WHERE id=" . $Row['Sid'];
      $Sresult = mysql_query($Query, $Link);
      $Srow = mysql_fetch_array($Sresult);
      // etcetera, rest doesn't matter
?>
The $Query assignment on the first line within the while loop is failing, and firther examination using print_r($Row) and print($Query) statements shows that $Row is empty and $Query is merely (as you would expect what with $Row being empty) "SELECT * FROM Stores WHERE id="

Note, however, that the while loop is iterating the expected number of times. That is, when the initial query returns two rows the while loop iterates twice.

But if I leave off the second condition like so:

Code: Select all

<?php
while ($Row = mysql_fetch_array($Result))
{    $Query = "SELECT * FROM Stores WHERE id=" . $Row['Sid'];
?>
then $Row and Query are completed correctly.

I can use LIMIT in the query, of course, which is actually a better way to do the process, and there are several other workarounds. But, why does the addition of the second condition kill the first?
:?:

Posted: Thu Dec 25, 2003 12:21 am
by volka
try this loop

Code: Select all

<?php
$arr = array('Sid'=>1); // an dummy array
$Cntr = 0;

while ($Row = $arr && $Cntr < 
{
	echo gettype($Row);	
	$Cntr += 1;
}
?>
and you will find that php evaluates your expression $Row = mysql_fetch_array($Result) && $Cntr < 8 different than you want it. It assigns wether mysql_fetch_array($Result) && $Cntr < 8 is true or false to $Row. the return-value of mysql_fetch_array($Result) is casted to boolean, if this is TRUE $Cntr < 8 is evaluated and both booleans are AND-combined.
You want:
- assign $Row the return value of mysql_fetch_array
- if this is != false AND $Cntr < 8 stay in loop
try

Code: Select all

while (false!==($Row=mysql_fetch_array($Result)) && $Cntr <

Posted: Thu Dec 25, 2003 8:17 am
by Bill H
Thank you volka. Based on what you said, I assumed this would work:

Code: Select all

<?php
while (($Row = mysql_fetch_array($Result)) && $Cntr < 
{    $Query = "SELECT * FROM Stores WHERE id=" . $Row['Sid'];
      // etcetera, etcetera
?>
and sure enough it does.
8)