Mysqli_fetch_assoc($result), pointer moves to the next record. Is there any way to reset the pointer to the start of the query result?

mysql, mysqli, php

Solution

So I was stuck with this problem at work today, and the only solution I initially found was to re-query, or use temporary copy of mysql result in a variable. Neither of which were appealing.

There is a much simpler solution to this which is mysql_data_seek.

Basic syntax is mysqli_data_seek(data,row)

So in this case you just do

mysqli_data_seek($result,0);
$row=mysqli_fetch_assoc($result);// Will now return the first row.

In a similar way you could loop through it again too.

It works similarly with mysql_data_seek. Hope it was helpful.

Problem

Have a look at this code Suppose you are looping through a set of mysql query results in php ``` while($temp = mysqli_fetch_assoc($result)) { echo $temp['id']; // ID Column } ``` When you do $temp=mysqli_fetch_assoc($result), basically the pointer moves to the next record. Is there any way to reset the pointer to the start of the query? As after the end of this loop mysqli_fetch_assoc($result) will only return empty rows, making it unusable again. So what's the possible solution?

Original source