Home » Mysql » How to go through mysql result twice?

How to go through mysql result twice?

Posted by: admin November 1, 2017 Leave a comment

Questions:

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?

Questions:
Answers:

Try whether mysql_data_seek() does what you need.

mysql_data_seek() moves the internal
row pointer of the MySQL result
associated with the specified result
identifier to point to the specified
row number. The next call to a MySQL
fetch function, such as
mysql_fetch_assoc(), would return that
row.

row_number starts at 0. The row_number
should be a value in the range from 0
to mysql_num_rows() – 1. However if
the result set is empty
(mysql_num_rows() == 0), a seek to 0
will fail with a E_WARNING and
mysql_data_seek() will return FALSE

Questions:
Answers:

You can use mysql_data_seek to move the internal pointer to the beginning of the data set. Then, you can just iterate through it again.

Questions:
Answers:

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?

Questions:
Answers:

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   
}

Questions:
Answers:

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.