获取带有 mysqli 结果的行数组

2021-12-25 00:00:00 php mysqli

我需要从结果对象中获取所有行.我正在尝试构建一个包含所有行的新数组.

I need to get all the rows from result object. I’m trying to build a new array that will hold all rows.

这是我的代码:

$sql = new mysqli($config['host'],$config['user'],$config['pass'],$config['db_name']);
if (mysqli_connect_errno())
{
    printf("Connect failed: %s
", mysqli_connect_error());
    exit();
}
$query = "SELECT domain FROM services";
$result = $sql->query($query);           
while($row = $result->fetch_row());
{
    $rows[]=$row;
}
$result->close();
$sql->close();
return $rows;

$rows 应该是包含所有行的新数组,但我得到了一个空数组.

$rows is supposed to be the new array that contains all, rows but instead I get an empty array.

知道为什么会这样吗?

推荐答案

你有一个轻微的语法问题,即一个错误的分号.

You had a slight syntax problem, namely an errant semi-colon.

while($row = $result->fetch_row());

注意到末尾的分号了吗?这意味着后面的块没有在循环中执行.摆脱它,它应该可以工作.

Notice the semi-colon at the end? It means the block following wasn't executed in a loop. Get rid of that and it should work.

另外,你可能想让mysqli报告它遇到的所有问题:

Also, you may want to ask mysqli to report all problems it encountered:

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$sql = new mysqli($config['host'], $config['user'], $config['pass'], $config['db_name']);

$query = "SELECT domain FROM services";
$result = $sql->query($query);
$rows = [];
while($row = $result->fetch_row()) {
    $rows[] = $row;
}
return $rows;

相关文章