Jump to content

Help setting up a for loop counting mysql_num_rows.


Guest convention

Recommended Posts

Guest convention
I made a while loop that displays all of the entries in the specified table (shown below), and I need to set up a for loop that assigns an incrementing number to each database entry. How could I do this? I tried using this for loop:

[code]
dbconnect();
$query = mysql_query("SELECT * FROM table_name ORDER BY id DESC");
while ($row = mysql_fetch_array($query)) {
      for ($i=1; $i<count(mysql_num_rows($query)); $i++) {
            echo $i."<br>";
            echo $row['field_name'];
            // Other statements...
      }
}
[/code]

but the whole thing disappears. And if I assign 0 to $i, then the number 0 is just displayed for every table entry. Any way to fix this?

Thank you. :)
[color=blue]mysql_num_rows($query)[/color] returns an int value, that contains the number of rows. You don't need to use count() function.

while ($row = mysql_fetch_array($query)) {
       for ($i=1; $i<[color=blue]mysql_num_rows($query)[/color]; $i++) {
             echo $i."<br>";
             echo $row['field_name'];
             // Other statements...
       }
}
Guest convention
Thank you for your help, dymon. However, now every single database entry loops 26 times each! (There are 26 entries in the database.) Here's what the output now looks like:

1. Entry One
2. Entry One
3. Entry One
...
1. Entry Two
2. Entry Two
3. Entry Two
...
1. Entry Three
2. Entry Three
3. Entry Three
...
You would better do like this, just a simple inc variable:

$count = 1;
while ($row = mysql_fetch_array($query)) {
            echo $count." ";
            echo $row['field_name'];
            $count++;
            // Other statements...
}

This should work.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.