Maintain a counter while looping a query result set
Asked Answered
S

3

6

I have the following:

$counter = 1;   
while ($row = mysql_fetch_assoc($result)) {
    $counter2 = $counter++;
    echo $counter2 . $row['foo'];
}

Is there an easier way to get 1,2,3 etc for each result or is this the best way?

Shopper answered 22/5, 2011 at 10:35 Comment(1)
Why aren't you just using the $counter variable?Ichneumon
U
21

You don't need $counter2. $counter++ is fine. You can even do it on the same line as the echo if you use preincrement instead of postincrement.

$counter = 0;   
while($row= mysql_fetch_assoc($result)) {
    echo(++$counter . $row['foo']);
}
Uncourtly answered 22/5, 2011 at 10:40 Comment(2)
Why did you get an upvote? You didn't show him his first error ($counter=2)?Marmion
He was postincrementing $counter, so $counter2 would get the value of $counter before it gets incremented. This version is using preincrementing, so $counter would get the value 1 before it's echoed for the first time.Uncourtly
B
17

I know it's not exactly what you have asked for - but why don't you simply use a for-loop instead of while?

for ($i = 0; $row = mysql_fetch_assoc($result); ++$i) {
    echo $i . $row['foo'];
}
Bey answered 22/5, 2011 at 11:6 Comment(0)
B
0

For a long time:

  • the mysql API has been obsolete and
  • the mysqli API's result set object has been traversable via foreach() as if an array of associative rows.

Instead of maintaining the counter manually, just access the index that the foreach() provides.

Code: (Demo)

$sql = <<<SQL
SELECT *
FROM your_table
ORDER BY lastname, firstname
SQL;

foreach ($mysqli->query($sql) as $i => $row) {
    printf(
        "<div>%d: %d, %s, %s</div>\n",
        $i + 1,
        $row['id'],
        $row['firstname'],
        $row['lastname']
    );
}
Bicuspid answered 10/11, 2023 at 10:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.