简体   繁体   English

获取具有 mysqli 结果的行数组

[英]get array of rows with mysqli result

I need to get all the rows from result object.我需要从结果 object 中获取所有行。 I'm trying to build a new array that will hold all rows.我正在尝试构建一个包含所有行的新数组。

Here is my code:这是我的代码:

$sql = new mysqli($config['host'],$config['user'],$config['pass'],$config['db_name']);
if (mysqli_connect_errno())
{
    printf("Connect failed: %s\n", 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 is supposed to be the new array that contains all, rows but instead I get an empty array. $rows应该是包含所有行的新数组,但我得到一个空数组。

Any ideas why this is happening?任何想法为什么会发生这种情况?

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.摆脱它,它应该可以工作。

Also, you may want to ask mysqli to report all problems it encountered:此外,您可能希望 mysqli 报告它遇到的所有问题:

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;

Newest versions of mysqli have some improvements that can simplify such a task.最新版本的 mysqli 有一些改进,可以简化这样的任务。

First, of all, there is a useful function to return an array with all rows returned by a query,mysqli_fetch_all()首先,有一个有用的函数可以返回一个包含查询返回的所有行的数组,mysqli_fetch_all()
It means in case you need a simple enumerated array, the code would be much simpler:这意味着如果您需要一个简单的枚举数组,代码会简单得多:

$query = "SELECT domain FROM services";
$result = $sql->query($query);     
return $result->fetch_all(MYSQLI_ASSOC);

or even all in one line,甚至都在一条线上,

return $sql->query("SELECT domain FROM services")->fetch_all(MYSQLI_ASSOC);

However, if you need to use some column to index the resulting array, you still need a while loop like this:但是,如果您需要使用某些列来索引结果数组,您仍然需要这样的 while 循环:

$query = "SELECT id, domain FROM services";
$result = $sql->query($query);
$data = [];
while ($row = $result->fetch_assoc()) {
  $data[$row['id']] = $row;
}

Note that you should always initialize an array before filling it up, because such a variable could already exist.请注意,您应该始终在填充数组之前对其进行初始化,因为这样的变量可能已经存在。

Also, mysqli_result class is now Traversable.此外, mysqli_result类现在是可遍历的。 It means you can use it in the foreach loop right away, as though it's an array contains all rows from the database:这意味着您可以立即在 foreach 循环中使用它,就好像它是一个包含数据库中所有行的数组一样:

$query = "SELECT domain FROM services";
$result = $sql->query($query);
foreach ($result as $row) {
    echo $row['domain'];
}

But it is actually just a syntax sugar for the while loop - you cannot access values of this "array" directly, which makes this feature of a little use actually.但它实际上只是 while 循环的语法糖——你不能直接访问这个“数组”的值,这使得这个特性实际上有点用处。

Obligatory notes.强制性说明。

This question is a decade old, and the way a connection is made and the query is performed, both in the question and the accepted answer, are obsoleted and frowned upon nowadays.这个问题已有十年之久,在问题和接受的答案中建立联系和执行查询的方式如今已过时且不受欢迎。

When a connection is made, there are several things to keep in mind.建立连接时,需要记住几件事。 I wrote an article on how to connect with mysqli properly that provides a correct connection example emphasizing on the following issues:我写了一篇关于如何正确连接mysqli的文章,提供了一个正确的连接示例,强调以下问题:

  • a proper error reporting mode must be set必须设置正确的错误报告模式
  • a proper character set must be set必须设置正确的字符
  • no manual error reporting code should be ever used (like die(mysqli_connect_error()) )不应使用手动错误报告代码(如die(mysqli_connect_error())
  • a connection has to be made only once , in a separate file, and then just included into every script that needs a database interaction.连接只需在单独的文件中建立一次,然后只需包含在需要数据库交互的每个脚本中即可。 in case a database code is used in a function, a connection variable must be passed in as a function parameter.如果在函数中使用数据库代码,则必须将连接变量作为函数参数传入。

When it goes to running a query, there are several things to keep in mind as well:在运行查询时,还需要记住几件事:

  • when even a single variable is used in the query, a prepared statement must be used instead of mysqli_query()即使在查询中使用单个变量时,也必须使用准备好的语句而不是mysqli_query()
  • as a result, a special function called mysqli_stmt_get_result() should be used in order to use familiar fetch functions to get the resulting rows.因此,应该使用一个名为mysqli_stmt_get_result()的特殊函数,以便使用熟悉的 fetch 函数来获取结果行。 In case this function is not available you are probably to tick some checkbox in your cpanel (look for one labeled mysqlnd ).如果此功能不可用,您可能需要在 cpanel 中勾选某个复选框(查找标记为mysqlnd的复选框)。
  • given a prepared statement with mysqli, although being obligatory, takes a lot code to write, it is advised to use a helper function for mysqli that would perform most of work automatically and make a mysqli prepared statement a smooth as a regular query.给定一个带有 mysqli 的预处理语句,虽然是强制性的,但需要编写大量代码,建议使用mysqli 的辅助函数,它会自动执行大部分工作,并使 mysqli 预处理语句像常规查询一样平滑。
  • no manual error reporting code should be ever used (like die(mysqli_error()) ).不应使用手动错误报告代码(如die(mysqli_error()) )。 Thanks to the proper error mode, mysqli will report all errors automatically.由于正确的错误模式,mysqli 将自动报告所有错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM