[英]Calling a function within the parameter of while loop in PHP
我在这个概念上停留了大约5个小时,这真的让我感到沮丧。
$result = $mysqli->query("SELECT col FROM table");
while($row = $result->fetch_assoc()){
echo $row['data'];
}
我知道该函数一次只能获取一行,但是我不了解循环重置时如何调用它。 如何在$row = $result->fetch_assoc
? 另外,如果$row
为null,此条件如何评估为true?
好的,这是对您的简单测试,
让我们拥有一个值为null
的array
,如下所示,
$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
,如上面的示例所示。
但是当你看到它就会返回true
为$result
,因为$result
实际上已经价值分配,这是true
。
因此条件将得到满足。
简而言之,while循环条件正在寻找true
:
while(true){
//do this
}
因此,直到该表达式$row = $result->fetch_assoc()
解析为true
$row = $result->fetch_assoc()
,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.php
http://php.net/manual/en/mysqli-result.fetch-assoc.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.