How to pass mysql result twice?

For some reason, I need to execute mysql result set twice. Is there any way to do this? I don’t want to run the query twice, and I don’t want to rewrite the script so that it stores the strings somewhere and then reuses them later.

+46
php mysql
Jun 22 2018-11-11T00:
source share
7 answers

Here's 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 must say that this does not seem to be the right way to handle this. Why not do the processing in the first loop?

+73
Jun 22 '11 at 11:45
source share

Try mysql_data_seek () doing what you need.

mysql_data_seek () moves the internal MySQL result string pointer to the identifier associated with the specified result, pointing to the specified row number. The next MySQL fetch call, for example mysql_fetch_assoc (), will return this string.

row_number starts with 0. row_number_number must be a value ranging from 0 to mysql_num_rows () - 1. However, if the result set is empty (mysql_num_rows () == 0), a search of 0 with an error of E_WARNING and mysql_data_seek () will return FALSE

+7
Jun 22 '11 at 11:44
source share

You can use mysql_data_seek to move the internal pointer to the beginning of the dataset. Then you can simply repeat it again.

+2
Jun 22 2018-11-11T00:
source share

I confess I have not tried this, but you tried after your first iteration

 mysql_data_seek($queryresult,0); 

go to first record?

+2
Jun 22 2018-11-11T00:
source share

An alternative to data retrieval is to store values ​​in 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 } 
+1
Jun 22 '11 at 11:50
source share

Well, you can always count the number of lines read and then do something like this:

 if (rownumber == mysql_num_rows($result)) { mysql_data_seek($result, 0); } 

I don’t know why you need it, but here it is.

0
Jun 22 '11 at 11:47
source share

For mysqli you should do the following:

 $result= $con->query($sql); // $con is the connection object $result->data_seek(0); 
0
Dec 27 '17 at 6:12
source share



All Articles