Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While loop VS. $sqlResult -> fetch_all(MYSQLI_ASSOC) ;

Not exactly sure why but I've seen this come up a number of 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 function of fetch_all

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

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

return $result->fetch_all(MYSQLI_ASSOC);

Wouldn't this render the while loop unnecessary? Any advantages? Speed differences?

like image 949
Joe Avatar asked Jan 10 '14 22:01

Joe


2 Answers

some valid statements here already.. but just to add to it on the mysqli_fetch_all documentation it states (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.

the part in bold implies that if he is doing some processing after each fetch_assoc:

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

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

}

he could get better performance than using the mysqli_fetch_all function(which would have to loop through to get all rows), and then doing another loop for processing each row.

as far as some other speed analysis this blog post -> http://blog.ulf-wendel.de/2007/php-mysqli_fetch_all/ is a bit dated (2007) but does an ok job of comparing the two methods.

like image 58
KorreyD Avatar answered Nov 12 '22 07:11

KorreyD


It could have been it was implemented before $mysqli came along, then $mysqli came along, along with the fetch_all functionality and the developer was lazy and saw that that would be the easiest way to update the code.

like image 25
frosty11x Avatar answered Nov 12 '22 06:11

frosty11x