我正在从 MYSQL 数据库中获取数据并循环遍历结果,但它只返回一行!!!谁能解释一下哪里出了问题
function getAll()
{
global $con;
$SQL = "SELECT * FROM users";
$stmt = $con->query($SQL);
if($stmt->num_rows > 0){
while($row = $stmt->fetch_row())
{
return $row;
}
}
}
最佳答案
返回应该在 while 循环之外!
这是获取所有行的方法:
function getAll()
{
global $con;
$SQL = "SELECT * FROM users";
$stmt = $con->query($SQL);
if($stmt->num_rows > 0){
$arr = array();
while($row = $stmt->fetch_row())
{
$arr[] = $row;
}
return $arr;
}
}
或者你可以像这样返回一个生成器并循环:
function getAll()
{
global $con;
$SQL = "SELECT * FROM users";
$stmt = $con->query($SQL);
if($stmt->num_rows > 0){
while($row = $stmt->fetch_row())
{
yield $row;
}
}
}
在这里查看结果!
echo '<pre>';
foreach (getAll() as $value) {
print_r($value);
}
关于php - 为什么 PHP 函数只返回来自 mysql 的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44297349/