views:

1084

answers:

2

One thing that has always bugged me is that when checking my php scripts for problems I get the warning "bool-assign : Assignment in condition" and I get them a lot. e.g.:

$guests = array();
$sql = "SELECT * FROM `guestlist`";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result))
    $guests[] = $row['name'];

Is there a different way to get multiple or all rows into an object or array? Or is there nothing wrong with this method?

+5  A: 

try doing this instead:

$guests = array();
$sql = "SELECT * FROM `guestlist`";
$result = mysql_query($sql);
while(($row = mysql_fetch_assoc($result)) !== false)
    $guests[] = $row['name'];

I believe php is warning because of the $row = mysql_fetch_assoc($result) not returning a boolean.

Jeremy Stanley
Actually, it's a code smell - PHP couldn't care less about the type of the result as long as it's not runtime convertible to false ("0",0, or false). Your script checker is just being paranoid because it's a common problem for rookies in languages with C-like syntax.
firebird84
+3  A: 

Actually, I believe it's warning because you could be making a mistake. Normally in a conditional, you mean to do:

if (something == something_else)

But it's easy to make a mistake and go:

if (something = something_else)

So it's likely warning you. If PHP is anything at all like C, you can fix your problem with a set of parentheses around your statement, like so:

while(($row = mysql_fetch_assoc($result)))

I believe Jeremy's answer is slightly off, because PHP is loosely typed and generally doesn't bother with such distinctions.

Dan Fego
I believe our answers are both functionally identical; yours is effectively saying "while(($row = mysql_fetch_assoc($result)) === true)". I would argue that the "!== false" / "=== true" adds to the readability and reasoning for it working with/without the parantheses.
Jeremy Stanley
Yes it's just a warning and works fine, however I was not sure if I was missing some alternative much simpler way (even though this way seems the simplest to me)Regards
Moak
I was just addressing the specific warning at hand. It's warning him because there's an "assignment in condition", i.e. a = where it's generally expecting a ==. This just makes it see it as whatever the result from the parens is.
Dan Fego