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. :)
Link to comment
Share on other sites

[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...
       }
}
Link to comment
Share on other sites

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
...
Link to comment
Share on other sites

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.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.