問題描述
警告:分配條件 (Warning: Assignment in condition)
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.
For example:
$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?
參考解法
方法 1:
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.
方法 2:
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.
(by Moak、Jeremy Stanley、Dan Fego)