downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

mysql_db_name> <mysql_create_db
[edit] Last updated: Fri, 25 May 2012

view this page in

mysql_data_seek

(PHP 4, PHP 5)

mysql_data_seekDéplace le pointeur interne de résultat MySQL

Description

bool mysql_data_seek ( resource $result , int $row_number )

mysql_data_seek() déplace le pointeur interne de résultat, dans le résultat associé à l'identifiant de résultat result_identifier. Il le fait pointer à la ligne row_number. Le prochain appel à une fonction MySQL de récupération de données, comme la fonction mysql_fetch_assoc() retournera cette ligne.

row_number commence à 0. row_number doit être une valeur qui va de 0 à mysql_num_rows() - 1. Cependant, si le résultat est vide, un row_number de 0 échouera avec une erreur E_WARNING et mysql_data_seek() retournera FALSE.

Liste de paramètres

result

La ressource de résultat qui vient d'être évaluée. Ce résultat vient de l'appel à la fonction mysql_query().

row_number

La position de la ligne désirée pour le nouveau pointeur de résultats.

Valeurs de retour

Cette fonction retourne TRUE en cas de succès ou FALSE si une erreur survient.

Exemples

Exemple #1 Exemple avec mysql_data_seek()

<?php
$link 
mysql_connect('localhost''mysql_user''mysql_password');
if (!
$link) {
    die(
'Connexion impossible : ' mysql_error());
}
$db_selected mysql_select_db('sample_db');
if (!
$db_selected) {
    die(
'Sélection de base de données impossible : ' mysql_error());
}
$query 'SELECT nom_famille, prenom FROM amis';
$result mysql_query($query);
if (!
$result) {
    die(
'Requête Ã©chec : ' mysql_error());
}
/* Récupération des lignes en ordre inverse */
for ($i mysql_num_rows($result) - 1$i >= 0$i--) {
    if (!
mysql_data_seek($result$i)) {
        echo 
"Ne peut pointer vers la ligne $i : " mysql_error() . "\n";
        continue;
    }

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

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

mysql_free_result($result);
?>

Notes

Note: Alternatives suggérées

L'utilisation de cette extension est déconseillée. A la place, l'extension MySQLi ou PDO_MySQL devrait être utilisée. Voir aussi MySQL : choisir une API pour plus d'information.

Les alternatives à à cette fonction sont :

Note:

La fonction mysql_data_seek() peut être utilisée en conjonction avec mysql_query(), mais pas avec la fonction mysql_unbuffered_query().

Voir aussi



mysql_db_name> <mysql_create_db
[edit] Last updated: Fri, 25 May 2012
 
add a note add a note User Contributed Notes mysql_data_seek
saeed at photobookworldwide dot com 25-Nov-2011 06:30
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;
?>
webmail7 at suddenlink dot net 29-Apr-2009 10:48
The mysql_query() function using the SELECT, SHOW, DESCRIBE, EXPLAIN or other statements returning a resultset, by default uses a TABLES INDEX, or simply the RECORD INSERT ORDER, in creating the resultset.

When using the mysql_data_seek() function along with a mysql_query() function using the SELECT, SHOW, DESCRIBE, EXPLAIN or other statements returning a resultset, and your desire is to SELECT A SPECIFIC ROW based upon the CONTENTS of a SPECIFIC FIELD then be sure to use the ORDER statement in your query or the mysql_data_seek() function may have unpredictable results.

Example (Find Last Record):

==============================================

<?php

$query
="SELECT * FROM `team` ORDER BY `team`.`id` ASC";
$result=mysql_query($query);
$last_row = mysql_num_rows($result) - 1;
if (
mysql_data_seek($result, $last_row)) { //Set Pointer To LAST ROW in TEAM table.

    
$row = mysql_fetch_row($result); //Get LAST RECORD in TEAM table
    
$id = $row[0] + 1; //New Team ID Value
     // more code here ...

} else { //Data Seek Error

   
echo "Cannot seek to row $last_row: " . mysql_error() . "\n";       

}

?>

==============================================

** Note:

1. The above example code relates to a MYSQL table named 'team' similar to this:

+-ID-+ TEAM NAME-+
| 49 |  Team 49  |
| 33 |  Team 33  |
| 84 |  Team 84  |
| 07 |  Team 07  |
+----+-----------+
** Records shown in the order inserted (i.e. TABLE NOT INDEXED)

2. In the above example code the field named ID is NOT set to AUTO-INCREMENT (i.e. field value set programmatically).

3. Wanting to insert a new team with a team number higher that the highest team number used, simply using the following code snippet

==============================================

<?php

$query
="SELECT * FROM `team`";

?>

==============================================

resulted in an ERROR when using the mysql_data_seek() function  to select the record with the highest ID value.

4. Use of the ORDER statement in the query corrected the error/problem.

Hope this helps someone.
Daniel 28-Aug-2008 02:59
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;
    }
?>
Guy Gordon 27-Jun-2007 01:26
I needed to "peek" at the next record in order to see if fetching it would go too far.  So I want to do a fetch, followed by seek(-1).
 
I could find no function to move the internal row pointer relative to it's current position, or to retrieve it as a row number as required by mysql_data_seek().  This limits the function's usefulness to resetting the row to 0, unless you track the row number yourself.

If you use a While loop to step through the results, you can increment a tracking index at the bottom of the loop.  But be sure never to use Continue; which would bypass your index.  And document this restriction for the person who needs to maintain your code.  It's probably better to use a For loop, which makes the index explicit. 

In either case be sure to range check the index when you manipulate it.  E.G. When I "peek" at the next record I must check for index>=count (end of data).  Or if I decrement the index, make sure it does not go negative.  Again, document why you are coding it this way, so the next programmer doesn't "correct" the inelegant code.
30-May-2006 01:52
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
}

?>
jonybd at yahoo dot com 27-Jun-2005 05:40
/*
    helpfull for real time databases query
    - Query one time
    - Retreive data twice from the same query
    - mysql_data_seek *

*/

include("p_MySql_Connection.php");

$v_Query    =     "SELECT f1 from t1";
           
$v_Result     =     mysql_query($v_Query, $v_RS);

/*
    First loop for one single query
*/
while ($row = mysql_fetch_array($v_Result,MYSQL_NUM)) {
    $v_total = $v_total + $row[1];
}
    echo $v_total;
           

/*
    Retreive data
*/
$v_Re     =     mysql_data_seek($v_Result,0);
if (!$v_Re){
    echo 'MySql data seek Error' .  mysql_error();
}

/*
    Second loop for one single query
*/           
while ($row = mysql_fetch_array($v_Result,MYSQL_NUM)) {
    echo $row[0];

}
arturo_b at hotmail dot com 20-Apr-2005 08:53
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.
b.steinbrink at g m x dot de 08-Dec-2004 11:09
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
kennethnash1134 at yahoo dot com 26-Mar-2004 12:12
/*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

 
show source | credits | sitemap | contact | advertising | mirror sites