I have a problem with the following blocks of code. I cannot have them both in the same page, or the last one fails (doesn’t matter if they change place, the last one fails). If I comment out one (regardless of which) then the other one works. So it doesn’t look like an issue with the actual code perhaps?
Is it not possible to run these two in the same page? I am obviously doing something wrong, so please help me point out what it is.
while( $test = sqlsrv_fetch_array( $data, SQLSRV_FETCH_ASSOC) ) {
if ($_GET['unit'] == '15min') { $newDate = $test['dt']->format('H:i:s'); }
if ($_GET['unit'] == 'hour') { $newDate = $test['dt']->format('m/d H:i'); }
if ($_GET['unit'] == 'day') { $newDate = $test['dt']->format('Y/m/d'); }
$dates[] = $newDate;
$values[] = $test[$pick_graph];
}
and the second one
while( $row = sqlsrv_fetch_array( $data, SQLSRV_FETCH_ASSOC) ) {
$newDate = $row['dt']->format('Y/m/d_H:i:s');
echo '<tr>'.
'<td>'.$row['net']."</td>".
'</tr>';
}
There’s no error message or anything. When the second loop runs, it’s as if $data is empty or something as it doesn’t loop through anything, putting an echo in there doesn’t output anything.
Like a lot of patterns in computer science, such as file IO, the results from a query in most libraries is treated as a stream. You get get the results as they come, but you can’t skip backwards and you can’t start over without rerunning the query.
You can either run the query again, or cache the results in an array.
Then you can
foreachover the$cachein your two locations doing the same logic as you do in your question.Caching is the better option in most cases.
However, if you’re talking about a really large result set (1000s), you’re may be better off running the query twice since you only need to store in RAM one row at a time. Rows that have already been used will be garbage collected.
As in all performance things, if it matters that much, profile it both ways and determine which meets your objectives.