Jan 21 2010

MYSQL add counter in a query

Category: MySql,PhpGiulio Pons @ 12:13 am

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/>";
}
  • Share/Bookmark

Related posts:

  1. 10 PHP usefull functions for MySQL stuff
  2. 10 PHP usefull functions for MySQLi stuff (mysql improved)
  3. Execute Scalar and Execute Row for Php
  4. PHP to get enum/set values from mysql field
  5. PHP function to fix collation on database fields of MySQL

Tags: , , , ,

5 Responses to “MYSQL add counter in a query”

  1. Lesya says:

    Thank you for interesting information. I was searching this information for a long time.

  2. Scooby says:

    Super simple and efficient!!
    Great post!

  3. Sara says:

    Thank you! I added this page to bookmark)) I think would be useful …

  4. wayne says:

    thank you
    nice post. Do more

  5. Fahmi says:

    This is cool! nice post! bookmarked it :)

Leave a Reply