php - While循环VS。 $sqlResult -> fetch_all(MYSQLI_ASSOC) ;

标签 php mysqli standards

不太清楚为什么,但我今天已经多次看到这种情况。

global $connection;
$sql = "SELECT * FROM table";

$result = $connection->query($sql);

$rows = array();
while ($row = mysqli_fetch_assoc($result)) {

    $rows[] = $row;

}

return $rows;

为什么不直接使用 fetch_all 的内置函数

global $connection;
$sql = "SELECT * FROM table";

$result = $connection->query($sql);

return $result->fetch_all(MYSQLI_ASSOC);

这不会使 while 循环变得不必要吗? 有什么优势吗? 速度差异?

最佳答案

这里已经有一些有效的陈述.. 但只是在它声明的 mysqli_fetch_all 文档中添加它 ( http://www.php.net/manual/en/mysqli-result.fetch-all.php ):

As mysqli_fetch_all() returns all the rows as an array in a single step, it may consume more memory than some similar functions such as mysqli_fetch_array(), which only returns one row at a time from the result set. Further, if you need to iterate over the result set, you will need a looping construct that will further impact performance. For these reasons mysqli_fetch_all() should only be used in those situations where the fetched result set will be sent to another layer for processing.

粗体部分暗示如果他在每次fetch_assoc之后做一些处理:

while ($row = mysqli_fetch_assoc($result)) {

     $rows[] = $row;
     ... //im doing stuff with $row here

}

他可以获得比使用 mysqli_fetch_all 函数(必须循环获取所有行)然后执行另一个循环来处理每一行更好的性能。

就这篇博文的一些其他速度分析而言 -> http://blog.ulf-wendel.de/2007/php-mysqli_fetch_all/有点过时(2007 年),但在比较这两种方法方面做得不错。

关于php - While循环VS。 $sqlResult -> fetch_all(MYSQLI_ASSOC) ;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21055747/

相关文章:

php - Heroku 本地 : how to install support for Postgres

php - 使用 mysqli 更新表

php - MySQL SELECT 查询四舍五入到小数点后 12 位

c++ - Linux 中 Eclipse C/C++ 的 Makefile

php - 检测(在自定义错误处理程序中)PHP 错误是否实际上被 @ 抑制了

PHP 错误 : "The zip extension and unzip command are both missing, skipping."

php - 无法在 android 中使用 php 从本地主机获取数据

php - 我需要按字符串排序,但考虑的字符串位于两个 "/"之间或两个 "-"之间,该怎么做

git - 您在团队中使用哪些指南或标准进行版本控制?

c++ - 哪个是最好的、标准的(希望是免费的)C++ 编译器?