Sometimes I’ve needed to add a counter column in a query and I don’t want to add the column with php, so I’ve found this query to put the counter directly in the record set returned out from the query.
set @N = 0; SELECT @N := @N +1 AS number, name, surname FROM people;
To use it in PHP scripts you have to use 2 query statements:
mysql_query("set @N = 0;");
$rs = mysql_query("SELECT @N := @N +1 AS number, name, surname FROM people");
while ($r=mysql_fetch_array($rs)) {
echo $r['number']." - ".$r['name']." ".$r['surname']."<br/>";
}
