Which one of the options below is better
Option 1:
//control file:
$smpt = $con->query("SELECT id,name FROM customers");
//fetch all resuts
$results = array();
while ($row = $result->fetch_assoc()) {
$results[] = $row;
}
$smpt->close();
//Note: PHP version < 5.3.0 so I can't use just $results->fetch_all('MYSQLI_ASSOC');
//view file:
foreach($results as $key=>$value) {
//display results
}
unset($results);
Option 2:
//control file:
$smpt = $con->query("SELECT id,name FROM customers");
//fetch all resluts
//view file:
while($row = $result->fetch_assoc()) {
//display results
}
$smpt->close();
I am trying to completely separate the logic from presentation... Current I am using option 2 because with option 1 the script go through 2 loops. one to fetch data and the other to display them. But which one is better to use?
Thanks
Option 1 allows you to re-use the $data
variable so you can display the results twice, but the cost of this is that you potentially have a large amount of data stored in a variable. You can clear this by using unset($data)
once you are 100% sure you've finished with it.
Option 2 requires less loops (only one instead of two) and doesn't need a extra variable to store the data. The cost of this is that the while
loop can only be used once.
In the grand scheme of things, the differences in speed will be so minimal the user won't notice them, however if there are 20+ instances of this in once script then it could have a noticeable affect.
I would recommend Option 2 providing that you'd only need to use the while
loop once. Also, you could benchmark your scripts to see how they perform against one another.