How to navigate within a MySQL resultset

I have the results of a MySQL query obtained using PHP as follows
  $result = $handle->query( $query );

I can navigate from first to last record with a loop using
  $item = $result->fetch_assoc();

I need to know how to navigate freely among the records in the resultset.  
I have done recordset navigation in MS Access with VB and with Java.  Does PHP/MySQL support
moving the internal record pointer?  

Are there PHP functions for operating on $result other than fetch_assoc()?

I use mysqli( ... ) to make the database connection.

Thanks
crm-servAsked:
Who is Participating?
 
Roger BaklundConnect With a Mentor Commented:
Fetch all the records into an array, then navigate using the array.

$rows = array();
while($item = $result->fetch_assoc()) $rows[] = $item;

Yes, there are other functions, or rather "methods", as your $result variable is an instance of a class.

http://php.net/manual/en/class.mysqli-result.php

You can use data_seek() to navigate the result set directly, as an alternative to fetching everything in an array.
0
 
ALNMOOCommented:
try to use fetch_array instead of fetch_assoc to use number as index
http://www.php.net/mysql_fetch_array
0
 
crm-servAuthor Commented:
Thank you for the response.

How do I use 'number as an index'?  
0
 
NerdsOfTechTechnology ScientistCommented:
// where $result is query executed
$result = mysqli_query($conn, $query) or die ("Couldn't execute query.");

REFERENCE BY POINTER
====================
$row=mysqli_fetch_assoc($result);
current($row) // current row; initialized as first record of array automatically
next($row) // next row
prev($row) // previous row row
end($row) // last row

OR


FORNEXT
========
$count=0;
foreach($row=mysqli_fetch_assoc($result)){
 echo $row['fieldname']; // reference to a field within row. this loop iterated through all rows
 echo $count; // print count
 $count++; // increment count
}

OR

DIRECT INDEX
===========
$row=mysqli_fetch_assoc($result);
print_h $row[2]; // print out the second row directly
0
 
crm-servAuthor Commented:
I was looking for the data_seek() kind of functionality.  Thanks for the help with this.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.