When using PHP to operate a MySQL database, we often get query results through mysqli_query , and then use mysqli_fetch_assoc to read the data row by row. If you want to jump to a row in the result set and read the data, mysqli_result::data_seek comes in handy.
This article will explain how to use mysqli_result::data_seek and mysqli_fetch_assoc to read the specified row data in the result set.
mysqli_result::data_seek(int $offset) : Moves the internal pointer of the result set to the specified row (counting from 0).
mysqli_fetch_assoc(mysqli_result $result) : Get a row of data from the current pointer position and return the associative array.
Suppose you execute a query, get multiple results, and want to access a certain row of data randomly, rather than read it in order.
<?php
// Connect to the database
$mysqli = new mysqli("gitbox.net", "username", "password", "database");
// Check the connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Execute a query
$sql = "SELECT id, name, email FROM users";
$result = $mysqli->query($sql);
if ($result && $result->num_rows > 0) {
// Suppose we want to read the3Line data(Index from0start,That is,3Row is index2)
$targetRow = 2;
// Move the pointer to the target row
$result->data_seek($targetRow);
// Read the data of the current row
$row = $result->fetch_assoc();
// Output data
echo "ID: " . $row['id'] . "\n";
echo "Name: " . $row['name'] . "\n";
echo "Email: " . $row['email'] . "\n";
} else {
echo "No data was found";
}
// Close the connection
$mysqli->close();
?>
data_seek function
data_seek is to locate the result set pointer to the specified row, and the next time fetch_assoc is called, it will start reading from this row.
Line index starts at 0 <br> The row index count starts at 0. If you want to read the first line, data_seek(0) ; the third line is data_seek(2) .
Applicable scenario restrictions <br> Data_seek can only be used when using a result set that supports buffering. By default, mysqli_query returns a buffered result set.
Through the combination of mysqli_result::data_seek and mysqli_fetch_assoc , you can flexibly jump to read any row of data in the result set, avoiding the performance overhead of traversing the entire result set. Mastering this technique will help you write more efficient database access code.