W3docs

data_seek

In this article, we will focus on the mysqli_data_seek() function in PHP, which is used to move the result pointer to a specified row number in a result set. We

The mysqli_data_seek() function in PHP moves the result pointer to a specified row number in a result set. It is useful when you need to access a specific row without iterating through the entire result set. Note that row indices are zero-based, and the function returns true on success or false on failure.

Introduction to the mysqli_data_seek() function

The mysqli_data_seek() function is a built-in PHP function that moves the result pointer to a specified row number in a result set. This function is useful when you need to access a specific row in a result set, rather than iterating over the entire result set.

How to use the mysqli_data_seek() function

Using the mysqli_data_seek() function is straightforward. You just need to call the function on a valid result set and pass in the row index you want to move the result pointer to. Here is an example:

How to use the mysqli_data_seek() function?

<?php
$mysqli = mysqli_connect("localhost", "username", "password", "database");

$query = "SELECT * FROM my_table";
$result = mysqli_query($mysqli, $query);

if (!$result) {
    echo "Failed to execute query: " . mysqli_error($mysqli);
    exit();
}

// move result pointer to row 3 (index 2, since indices are zero-based)
if (!mysqli_data_seek($result, 2)) {
    echo "Seek failed";
    exit();
}

// fetch the data from row 3
$row = mysqli_fetch_assoc($result);

print_r($row);

mysqli_close($mysqli);
?>

In this example, we first connect to a MySQL database using the mysqli_connect() function. We then execute a query using the mysqli_query() function and store the result in a variable. We check if there was an error in the query using the mysqli_error() function. If there was an error, we output the error message and exit the script.

Next, we use the mysqli_data_seek() function to move the result pointer to the third row in the result set. Note that row indices are zero-based, so we pass 2 to access the third row. The function returns true on success; we check this return value to handle potential errors. Finally, we use the mysqli_fetch_assoc() function to fetch the data from the third row and store it in a variable. We output the variable using the print_r() function.

Conclusion

In conclusion, the mysqli_data_seek() function is a useful tool for accessing specific rows in a result set in PHP. For better performance, consider using SQL LIMIT and OFFSET clauses to fetch only the rows you need, as seeking rows in PHP can be inefficient for large result sets.

Practice

Practice

What is the primary function of the PHP method mysql_data_seek()?