mysqli provides a function that starts the query return row from an nth row as indicated. This can be done using mysqli_data_seek()
.
The mysqli_data_seek()
function will cause the result pointer in your query to be adjusted to an arbitrary row in the result-set. With this, you can point to a particular row and start to read your result from there.
OFFSET
To achieve what is described above, we can also use the OFFSET
clause to start out fetching from a certain row. The difference here is that with the OFFSET
clause, the query result skipped the first few rows as indicated in the offset.
With mysqli_data_seek()
all the results set as indicated from the query are available but you only want to fetch from a particular row downwards.
You can free up the result set later in your script. All the result set returned from the query will be available to you for use.
mysqli_data_seek(result,offset);
result
: This is the query result to be chopped.offset
: an integer indicating the row where you wish to start fetching contentsBelow is a diagrammatic representation of what is obtainable using the mysqli_data_seek()
function:
In the code below:
$result
.row number 14
, leaving it with row 15
downwards.mysqli_free_result()
function and the database connection closed.<?php$dbcon=mysqli_connect("localhost","user","password","dbname");// Check connectionif (mysqli_connect_errno()){echo "Failed to connect to MySQL: " . mysqli_connect_error();}// write a SELECT statement$sqlset="SELECT names,age FROM students ORDER BY age";//query the database with the SELECT statement.$result=mysqli_query($dbcon,$sqlset)// check that the query worked and run some codesif ($result){// Seek to row number 15mysqli_data_seek($result,14);// Fetch row$row=mysqli_fetch_row($result);printf ("names: %s age: %s\n", $row[0], $row[1]);/* Free result set so that you can now get all resultavailable and ready for use again.*/mysqli_free_result($result);}// close database connectionmysqli_close($dbcon);?>