Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is best to use, fetch_array(MYSQLI_ASSOC) or fetch_all(MYSQLI_ASSOC)?

Tags:

php

mysqli

They are two functions of mysqli_result.

  • fetch_array(): Fetch a result row.

In this way, query for each row to the database?

  • fetch_all(): Fetches all result rows.

And in this way, only query once to the database?

I do not know how to do it in the best way and the most efficient way.

Put examples:

1.-fetch_array():

$resultUsers = getAllUsers($db);
while($row = $resultUsers->fetch_array()){
     echo $row['name'];
}

2.- fetch_all():

$resultUsers = getAllUsers($db);
foreach ($resultUsers->fetch_all(MYSQLI_ASSOC) as $value) {
    echo $value['name'] . "<br>";
}

2.A.-

foreach (getAllUser($db)->fetch_all(MYSQLI_ASSOC) as $value) {
    echo $value['name'] . "<br>";
}

If there is a better way to do it, I hope your help.

like image 282
RodriKing Avatar asked Nov 08 '22 01:11

RodriKing


1 Answers

For your particular case you need fetch_all() moved inside, as a function called getAllUsers() should get you all users, not mysqli result.

So it should be

$allUsers = getAllUsers($db);

and then $allUsers sent to a template for the output like

<?php foreach ($allUsers as $user) { ?>
    <?=$user['name']?>
>?} ?>
like image 80
Your Common Sense Avatar answered Nov 15 '22 04:11

Your Common Sense