PHP 8.3.4 Released!

mysql_data_seek

(PHP 4, PHP 5)

mysql_data_seekПеремещает внутренний указатель в результате запроса

Внимание

Данный модуль устарел начиная с версии PHP 5.5.0, и удалён в PHP 7.0.0. Используйте вместо него MySQLi или PDO_MySQL. Смотрите также инструкцию MySQL: выбор API. Альтернативы для этой функции:

Описание

mysql_data_seek(resource $result, int $row_number): bool

mysql_data_seek() перемещает внутренний указатель результата запроса, с которым связан переданный дескриптор, к ряду с указанным номером. Следующий вызов к функции получения данных MySQL, такой как mysql_fetch_assoc(), вернёт именно его.

Нумерация row_number начинается с 0. row_number должен быть значением в диапазоне от 0 до mysql_num_rows() - 1. Однако, если результат пуст (mysql_num_rows() == 0), то попытка сдвига указателя к нулевому ряду завершится неудачей - будет вызвана ошибка уровня E_WARNING и mysql_data_seek() вернёт false.

Список параметров

result

Обрабатываемый результат запроса. Этот результат может быть получен с помощью функции mysql_query().

row_number

Желаемый номер ряда в полученном дескрипторе результата.

Возвращаемые значения

Возвращает true в случае успешного выполнения или false в случае ошибки.

Примеры

Пример #1 Пример использования mysql_data_seek()

<?php
$link
= mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!
$link) {
die(
'Ошибка соединения: ' . mysql_error());
}
$db_selected = mysql_select_db('sample_db');
if (!
$db_selected) {
die(
'Не удалось выбрать базу данных: ' . mysql_error());
}
$query = 'SELECT last_name, first_name FROM friends';
$result = mysql_query($query);
if (!
$result) {
die(
'Ошибка запроса: ' . mysql_error());
}
/* получение рядов в обратном порядке */
for ($i = mysql_num_rows($result) - 1; $i >= 0; $i--) {
if (!
mysql_data_seek($result, $i)) {
echo
"Не удалось переместиться к ряду $i: " . mysql_error() . "\n";
continue;
}

if (!(
$row = mysql_fetch_assoc($result))) {
continue;
}

echo
$row['last_name'] . ' ' . $row['first_name'] . "<br />\n";
}

mysql_free_result($result);
?>

Примечания

Замечание:

Функция mysql_data_seek() может быть использована только с mysql_query(), но не с mysql_unbuffered_query().

Смотрите также

  • mysql_query() - Посылает запрос MySQL
  • mysql_num_rows() - Возвращает количество рядов результата запроса
  • mysql_fetch_row() - Обрабатывает ряд результата запроса и возвращает массив с числовыми индексами
  • mysql_fetch_assoc() - Возвращает ряд результата запроса в качестве ассоциативного массива
  • mysql_fetch_array() - Обрабатывает ряд результата запроса, возвращая ассоциативный массив, численный массив или оба
  • mysql_fetch_object() - Обрабатывает ряд результата запроса и возвращает объект

add a note

User Contributed Notes 6 notes

up
6
kennethnash1134 at yahoo dot com
19 years ago
/*here is a nice function for converting a mysql result row set into a 2d array, a time saver if need small data from several rows, saves you from having to do Alot of queries... would be nice to have this built into PHP future versions :) */

// simple example query
$r=mysql_query("select user,id,ip from accounts limit 10");

//starts the for loop, using mysql_num_rows() to count total
//amount of rows returned by $r
for($i=0; $i<mysql_num_rows($r); $i++){
//advances the row in the mysql resource $r
mysql_data_seek($r,$i);
//assigns the array keys, $users[row][field]
$users[$i]=mysql_fetch_row($r);
}

//simple, hope someone can use it :)
// -Kenneth Nash
up
2
arturo_b at hotmail dot com
18 years ago
hello, this script would be easy to understand for those that are novice in php whose want to understand about this function:

the table "user" have 2 columns "id" and "name".
"user" content:
position 0: "id"=195342481 "name"='Arthur'
position 1: "id"=179154675 "name"='John'
>>position 2<<: "id"=157761949 "name"='April' >>third row<<
position 3: "id"=124492684 "name"='Tammy'
position 4: "id"=191346457 "name"='Mike'

<?php
mysql_connect
("localhost", "root")
mysql_select_db("test");
$sql = mysql_query("select * from user");
mysql_data_seek($sql, 2);
echo
"<table border=1>";
while (
$row = mysql_fetch_row($sql)){
echo
"<tr><td>$row[0]</td><td>$row[1]</td></tr>";
}
echo
"</tabla>";
?>

explanation:
mysql_data_seek move internal result pointer to the third row of table user. Thus mysql_fetch_row will begin by april?s row.
up
1
saeed at photobookworldwide dot com
12 years ago
Here, you can find the current pointer of selected row easily:

<?php
//selected row with id=4
$id = "4";

$result = mysql_query("select * from jos_components");

$num = mysql_num_rows($result);

for(
$i=0;$i<$num;$i++){

mysql_data_seek($result,$i);

$row = mysql_fetch_assoc($result);

if(
$row['id'] == $id){

$pointer = $i;
}


}

// current pointer for selected row
echo $pointer;
?>
up
-2
b.steinbrink at g m x dot de
19 years ago
to kennethnash1134 at yahoo dot com

your loop can be done like this as well and i guess this is faster:

$r=mysql_query("select user,id,ip from accounts limit 10");

unset($users); // Just to be sure
while($users[] = mysql_fetch_row);
array_pop($users); // Drop the last entry which is FALSE
up
-6
Daniel
15 years ago
Here is a simple function to "peek" at the position of the internal pointer in a query result:

<?php
function mysql_pointer_position($result_set) {
$num_rows = mysql_num_rows($result_set);
$i = 0;
while(
$result = mysql_fetch_array($result_set)) {
$i++;
}
$pointer_position = $num_rows - $i;

//Return pointer to original position
if($pointer_position <= $num_rows - 1) {
mysql_data_seek($result_set, $pointer_position);
}
return
$pointer_position;
}
?>
up
-7
Anonymous
17 years ago
A helpful note about the 'resource' data type.

Since the 'resource' variable is pointing to a row in a result set at any given time, you can think of it as being passed to this function by reference every time you pass it or assign it to a variable.

<?

$sql = "SELECT * from <table>";
$result = mysql_query($sql);
$temp_result = $result;

while ($row = mysql_fetch_assoc($temp_result)) {
// do stuff with $row
}

while ($row = mysql_fetch_assoc($result)) {
// This code will never run because the 'resource' variable is pointing past the end of the result set,
// even though it was *not* assigned by reference to $result2.
}

?>

Therefore, the following snipits are functionally identical:

<?

// Start snipit 1

$sql = "SELECT * from <table>";
$result = mysql_query($sql);

while ($row = mysql_fetch_assoc($result)) {
// do stuff with $row
}

mysql_data_seek($result, 0);

while ($row = mysql_fetch_assoc($result)) {
// do other stuff with $row
}

// Start snipit 2

$sql = "SELECT * from <table>";
$result = mysql_query($sql);
$temp_result = $result;

while ($row = mysql_fetch_assoc($temp_result)) {
// do stuff with $row
}

mysql_data_seek($result, 0);

while ($row = mysql_fetch_assoc($temp_result)) {
// do other stuff with $row
}

?>
To Top