note 71482 added to function.mysql-fetch-row

From: Date: Fri, 01 Dec 2006 01:19:00 +0000
Subject: note 71482 added to function.mysql-fetch-row
Groups: php.notes 
Request: Send a blank email to php-notes+get-120206@lists.php.net to get a copy of this message
Please be advised that the resource result that you pass to this function can be thought of as being passed by reference because a resource is simply a pointer to a memory location. Because of this, you can not loop through a resource result twice in the same script before resetting the pointer back to the start position. For example: ---------------- <?php // Assume We Already Queried Our Database. // Loop Through Result Set. while( $queryContent = mysql_fetch_row( $queryResult ) { // Display. echo $queryContent[ 0 ]; } // We looped through the resource result already so the // the pointer is no longer pointing at any rows. // If we decide to loop through the same resource result // again, the function will always return false because it // will assume there are no more rows. // So the following code, if executed after the previous code // segment will not work. while( $queryContent = mysql_fetch_row( $queryResult ) { // Display. echo $queryContent[ 0 ]; } // Because $queryContent is now equal to FALSE, the loop // will not be entered. ?> ---------------- The only solution to this is to reset the pointer to make it point at the first row again before the second code segment, so now the complete code will look as follows: ---------------- <?php // Assume We Already Queried Our Database. // Loop Through Result Set. while( $queryContent = mysql_fetch_row( $queryResult ) { // Display. echo $queryContent[ 0 ]; } // Reset Our Pointer. mysql_data_seek( $queryResult ); // Loop Again. while( $queryContent = mysql_fetch_row( $queryResult ) { // Display. echo $queryContent[ 0 ]; } ?> ---------------- Of course you would have to do extra checks to make sure that the number of rows in the result is not 0 or else mysql_data_seek itself will return false and an error will be raised. Also please note that this applies to all functions that fetch result sets, including mysql_fetch_row, mysql_fetch_assos, and mysql_fetch_array. ---- Server IP: 66.163.161.117 Probable Submitter: 84.36.10.130 ---- Manual Page -- http://www.php.net/manual/en/function.mysql-fetch-row.php Edit -- https://master.php.net/note/edit/71482 Del: integrated -- https://master.php.net/note/delete/71482/integrated Del: useless -- https://master.php.net/note/delete/71482/useless Del: bad code -- https://master.php.net/note/delete/71482/bad+code Del: spam -- https://master.php.net/note/delete/71482/spam Del: non-english -- https://master.php.net/note/delete/71482/non-english Del: in docs -- https://master.php.net/note/delete/71482/in+docs Del: other reasons-- https://master.php.net/note/delete/71482 Reject -- https://master.php.net/note/reject/71482 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#120206) next »