Jump to content


Help setting up a for loop counting mysql_num_rows.


  • Please log in to reply
4 replies to this topic

#1 Guest_convention_*

Guest_convention_*
  • Guests

Posted 15 October 2006 - 07:09 AM

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:

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...
       }
}

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. :)

#2 dymon

dymon
  • Members
  • PipPipPip
  • Advanced Member
  • 79 posts

Posted 15 October 2006 - 07:13 AM

mysql_num_rows($query) 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<mysql_num_rows($query); $i++) {
             echo $i."<br>";
             echo $row['field_name'];
             // Other statements...
       }
}
Web is the future ... desktop will die ...

#3 Guest_convention_*

Guest_convention_*
  • Guests

Posted 15 October 2006 - 07:29 AM

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

#4 dymon

dymon
  • Members
  • PipPipPip
  • Advanced Member
  • 79 posts

Posted 15 October 2006 - 07:33 AM

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.
Web is the future ... desktop will die ...

#5 Guest_convention_*

Guest_convention_*
  • Guests

Posted 15 October 2006 - 07:43 AM

Ah ha! Thank you so much!  ;D ;D




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users