Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 476
  • Last Modified:

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
0
crm-serv
Asked:
crm-serv
1 Solution
 
ALNMOOCommented:
try to use fetch_array instead of fetch_assoc to use number as index
http://www.php.net/mysql_fetch_array
0
 
Roger BaklundCommented:
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
 
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

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now