-1
while($qry_comment = mysql_fetch_array($sql_comment)) {
echo "#1,";
echo $qry_comment['content'];
echo "<br />";
}

i'm trying to make the number count up in the while loop, but i just don't know how. something with ++ , i tried a few ways but I couldn't make it work the right way. can anyone help me out here? thanks

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • Do you want to display each comment's number next to the comment, or do you want to count the total number of comments? – Nic Wortel Dec 10 '13 at 23:06
  • i got the number next to it. how can i make it count the total? – user2617739 Dec 10 '13 at 23:09
  • By the way, [you shouldn't use mysql_ functions](http://stackoverflow.com/q/12859942/1001110). Use [mysqli](http://www.php.net/mysqli) or [PDO](http://php.net/pdo) instead. – Nic Wortel Dec 10 '13 at 23:27
  • can you suggest me a link to an easy and understandable guide for mysqli or pdo? – user2617739 Dec 10 '13 at 23:42
  • I don't have a specific guide, but if you search Google for 'pdo beginners guide' or something like that, you'll find a lot of results. – Nic Wortel Dec 10 '13 at 23:52

2 Answers2

0

Just use a variable that increments on each loop iteration:

$counter = 1;
while($qry_comment = mysql_fetch_assoc($sql_comment)) {
  echo "#" . $counter . ",";
  echo $qry_comment['content'];
  echo "<br />";
  $counter++;
}
John Conde
  • 217,595
  • 99
  • 455
  • 496
0

There are multiple ways to increase the value of a variable with 1:

Arithmetic operators:

  • $a = $a + 1;
  • $a += 1;

Incrementing/Decrementing Operators:

  • $a++;
  • ++$a;

The location of the incrementing / decrementing operator determines when the calculation is executed. When using a pre-increment (++$a;), the variable is incremented, then returned. When using a post-increment ($a++;), the variable is returned first, and then incremented.

Example:

$a = 5;
echo $a++; // echoes '5'
echo $a;   // echoes '6'

$a = 5;
echo ++$a; // echoes '6'
echo $a;   // still echoes '6'

Of course, if you don't echo the value, it doesn't matter if you use $a++ or ++$a.

Returning to your case, you can use the following code:

$counter = 1;

while($comment = mysql_fetch_assoc($sql_comment)) {
    echo '#' . $counter++ . ','; // First echo $counter, then increment it
    echo $comment['content'];
    echo "<br />";
}

By the way, you can use MySQL instead of PHP to count the comments as well.

Community
  • 1
  • 1
Nic Wortel
  • 11,155
  • 6
  • 60
  • 79