So far the VS loop. $ sqlResult & # 8594; fetch_all (MYSQLI_ASSOC);

It’s not entirely clear why, but I saw that it appeared many times today.

global $connection; $sql = "SELECT * FROM table"; $result = $connection->query($sql); $rows = array(); while ($row = mysqli_fetch_assoc($result)) { $rows[] = $row; } return $rows; 

Why not just use the built-in fetch_all function

 global $connection; $sql = "SELECT * FROM table"; $result = $connection->query($sql); return $result->fetch_all(MYSQLI_ASSOC); 

Could this make the while loop unnecessary? Any benefits? Differences in speed?

+6
source share
2 answers

Perhaps this was implemented before $ mysqli appeared, then $ mysqli appeared, along with the fetch_all functionality, and the developer was lazy and saw that this would be the easiest way to update the code.

+1
source

some valid statements are already here ... but just to add to it, the mysqli_fetch_all documentation states ( http://www.php.net/manual/en/mysqli-result.fetch-all.php ):

Since mysqli_fetch_all () returns all rows as an array in one step, it can consume more memory than some similar functions, such as mysqli_fetch_array (), which returns only one row at a time from the result set. In addition, if you need to repeat the result set, you will need a loop design that will further affect performance. For these reasons, mysqli_fetch_all () should only be used in situations where the resulting result set will be sent to another level for processing.

the bold part implies that if it does some processing after each fetch_assoc:

 while ($row = mysqli_fetch_assoc($result)) { $rows[] = $row; ... //im doing stuff with $row here } 

it could get better performance than using the mysqli_fetch_all function (which should go through all the lines), and then do another loop to process each line.

as much as possible in another speed analysis, this blog post → http://blog.ulf-wendel.de/2007/php-mysqli_fetch_all/ is a bit dated (2007), but does a good job comparing the two methods.

+1
source

All Articles