mysql loop through table

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
MedaXis
Forum Newbie
Posts: 16
Joined: Tue Nov 12, 2002 12:49 pm
Location: the netherlands

mysql loop through table

Post by MedaXis »

hi all, I have a piece of php-code which I don't understand (it works though):

Code: Select all

$query = "SELECT * FROM guests ORDER BY id DESC";
$result = @mysql_query($query) or die("&error=".mysql_error());
$num_rows = mysql_num_rows($result);
if($num_rows > 0){
for($i = 0; $i < $num_rows; $i++)
&#123;
$row = mysql_fetch_array($result);
$name = $row&#1111;'name'];
...
...
...
...
the code goes on but this is the important part

how does $row know which item inside the array it should pick? I mean: there are more rows in the tableand it loops through the table, what is the point of th $i in the for loop if it's not even used?
I would have expected this: $name = $row[$]['name'] instead of the current line


Steve
User avatar
puckeye
Forum Contributor
Posts: 105
Joined: Fri Dec 06, 2002 7:26 pm
Location: Joliette, QC, CA
Contact:

Post by puckeye »

Code: Select all

$query = "SELECT * FROM guests ORDER BY id DESC"; 
$result = @mysql_query($query) or die("&error=".mysql_error()); 
$num_rows = mysql_num_rows($result); 
if($num_rows > 0)&#123; 
for($i = 0; $i < $num_rows; $i++) 
&#123; 
$row = mysql_fetch_array($result); 
$name = $row&#1111;'name']; 
...
$i is simply a counter for PHP to know where it's at... A simpler way to do the same thing is like this:

Code: Select all

$query = "SELECT * FROM guests ORDER BY id DESC"; 
$result = @mysql_query($query) or die("&error=".mysql_error()); 

$num_rows = mysql_num_rows($result); 
if($num_rows > 0)
&#123; 
     while ($row = mysql_fetch_array($result))
     &#123; 
           $name = $row&#1111;'name']; 
          ... 
     &#125;
&#125;
Using mysql_fetch_array returns either an array of all your fields in the table or FALSE if there are no more rows to recover.

mysql_fetch_array uses it's own internal counter to sift through the results that's why you can use $row['name'] to retrieve the content of the field named 'name', each time mysql_fetch_array is called it increments it's internal counter and populates $row with the next row's values...
MedaXis
Forum Newbie
Posts: 16
Joined: Tue Nov 12, 2002 12:49 pm
Location: the netherlands

Post by MedaXis »

does that mean I can't start counting on the second row in the table?

Steve
User avatar
puckeye
Forum Contributor
Posts: 105
Joined: Fri Dec 06, 2002 7:26 pm
Location: Joliette, QC, CA
Contact:

Post by puckeye »

MedaXis wrote:does that mean I can't start counting on the second row in the table?

Steve
Actually no,

You can start on the second, third or xth row.

Check this out: http://www.php.net/manual/en/function.m ... a-seek.php to move forward in your results.
Post Reply