Page 1 of 1

mysql loop through table

Posted: Mon Jan 20, 2003 12:58 pm
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

Posted: Mon Jan 20, 2003 2:06 pm
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...

Posted: Tue Jan 21, 2003 9:19 am
by MedaXis
does that mean I can't start counting on the second row in the table?

Steve

Posted: Tue Jan 21, 2003 9:39 am
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.