que-6ren">
gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 12:57:46 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com