Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing db value into php array and then looping through the array

Tags:

arrays

php

mysqli

What would the benefits be of storing db values into an array and then looping through the array vs just using a while loop?

Outputting db results to an array:

$records = array();

if($results = $db->query("SELECT name, address FROM town")) {
    if($results->num_rows) {
        while($row = $results->fetch_object()) {
            $records[] = $row;
        }
        $results->free();
    }
}

Loop through array:

foreach($records as $r) {
    $r->name; 
}

VS a simple While loop:

if($result = $db->query("SELECT name, address FROM town")) {
    if($count = $result->num_rows) {

        while($row = $result->fetch_object()) {
            echo $row->name, ' ', $row->address, '<br />';
        }

        $result->free();
    }
}
like image 290
user1040259 Avatar asked Feb 04 '26 00:02

user1040259


2 Answers

Just a while loop and printing the result is easy and fast, but in certain times you want to do more then just print the array and then it becomes handy if you already work with arrays.

like image 119
davejal Avatar answered Feb 06 '26 13:02

davejal


The most common use for this is freeing the resultset, allowing you to perform other db queries (updates, inserts...) before actually making any use of the results you got in the first place.

like image 34
Calimero Avatar answered Feb 06 '26 14:02

Calimero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!