PHP MySQL: using data_seek to fetch row

This entry is part 15 of 17 in the series PHP & MySQL

The data_seek function in PHP allow us to fetch a particular row.

Syntax:

bool mysqli_result::data_seek (int $offset)

Data_seek adjusts the result pointer to an arbitrary row specified by offset in the result.

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "root", "", "allartist");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s", mysqli_connect_error());
    exit();
}

$query = "select * from artist";
if ($result = $mysqli->query( $query)) {

    /* seek to row no. 4 */
    $result->data_seek(3);

    /* fetch row */
    $row = $result->fetch_row();

    printf ("Artiste: %s Album: %s Year: %s", $row[1], $row[2], $row[3]);

    /* free result set*/
    $result->close();
}

/* close connection */
$mysqli->close();
?>

The offset here is 3 and as it starts from index 0, it points to row 4 in the table.

This function can only be used with buffered results attained from the use of the mysqli_store_result() or mysqli_query() functions.

Here is the output after running the script above.

data_seek

Series Navigation<< PHP MySQL: Select a single record using fetch_assoc
PHP MySQL: Outputing data to HTML table I >>