我已经在这个概念上停留了大约 5 个小时,这真的让我感到沮丧。
$result = $mysqli->query("SELECT col FROM table");
while($row = $result->fetch_assoc()){
echo $row['data'];
}
我知道该函数一次只获取一行,但我不明白循环重置时如何调用它。$row = $result->fetch_assoc
怎么称呼?此外,如果 $row
为 null,则此条件的计算结果如何为 true?
好的,这是给你的简单测试,
让我们有一个具有价值的array
null
如下所示, $row = array('value' => null);
现在让我们使用if
条件进行检查
if($row)
{
echo "null is making variable value to true so condition will work.";
}
粘贴code
并run
它,我相信您会在if
条件中看到消息。
您的状况
您正在使用$result->fetch_assoc()
,因此如您所知,它将返回可能具有null
值的array
如上例所示。
但如您所见,它将返回$result
的true
,因为$result
实际上分配了值并且它是true
.
所以条件会得到满足。
简而言之,while 循环条件正在寻找true
:
while(true){
//do this
}
因此,在此表达式$row = $result->fetch_assoc()
解析为true
之前,while 循环将继续。
问题是什么时候会不是真的?当检索到所有行时。
如果 $row 为 null,则此条件的计算结果如何为 true?
其实不然。这就是重点。
给定您的代码:
while($row = $result->fetch_assoc()){
echo $row['data'];
}
循环条件可以重写为以下等效条件:
while (($row = $result->fetch_assoc()) != false) {
echo $row['data'];
}
换句话说,虽然$row
不是假的,但它将继续循环; null
也被认为是假的。
以下对代码的解释可能会对您有所帮助
// run the query. this returns a mysqli_result object on success.
// on failure query function returns false and you have to handle this condition.
$result = $mysqli->query("SELECT col FROM table");
// fetch_assoc() here you fetch one row at a time from the mysqli_result
// object into $row. this also moves the pointer to the next row
// so the next call returns the next row.
// This returns false when there is no more rows and exit your while loop
while($row = $result->fetch_assoc()){
echo $row['data'];
}
您可能想要参考
的链接
http://www.php.net/manual/en/class.mysqli-result.phphttp://php.net/manual/en/mysqli-result.fetch-assoc.php