Tuesday 6 November 2018

How to go through mysql result twice?

For whatever reason I need to go through a mysql result set twice. Is there a way to do it? I don't want to run the query twice and I don't want to have to rewrite the script so that it stores the rows somewhere and then reuses them later.

 Answers


This is how you can do it:
$result = mysql_query(/* Your query */);
while($row = mysql_fetch_assoc($result)){
 // do whatever here...
}

// set the pointer back to the beginning
mysql_data_seek($result, 0);
while($row = mysql_fetch_assoc($result)){
 // do whatever here...
}
However, I would have to say, this doesn't seem the right way to handle this. Why not do the processing within the first loop?



Alternative to the data seek is to store the values into an array:
$arrayVals = array();
$result = mysql_query(/* Your query */);
while($row = mysql_fetch_assoc($result)){
    $arrayVals[] = $row;
}

// Now loop over the array twice instead

$len = count($arrayVals);
for($x = 0; $x < $len; $x++) {
    $row = $arrayVals[$x];

    // Do something here    
}

$len = count($arrayVals);
for($x = 0; $x < $len; $x++) {
    $row = $arrayVals[$x];

    // Do something else here   
}



I confess I haven't tried this, but have you tried after your first iteration
mysql_data_seek($queryresult,0);
to go to the first record?



Well, you could always count the number of rows you read, and then do something like this:
if (rownumber == mysql_num_rows($result)) { mysql_data_seek($result, 0); }
Don't know why you would need to, but there it is.

0 comments:

Post a Comment