3

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();
    }
}

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.