PHP-MySQL-How to safely increment MySQL integer field?

John picture John · Jan 9, 2010 · Viewed 48k times · Source

I want to increment a field value safely using php and mysql.

  1. What type of table/field must I use?

  2. Is there a minimum version of MySQL I must use?

  3. What's the sql code for this, safe transaction for MySQL?

Answer

Chris Tonkinson picture Chris Tonkinson · Jan 9, 2010

By what type of "table" I assume you mean storage engine. Anything that supports mutations (i.e. not "archive" or "black hole")

Any numeric field will do (tinyint, int, float, etc). That said, there's no special PHP code, just the SQL for incrementing the desired field:

UPDATE table SET field = field + 1 WHERE [...]

If you want a transaction, then pack the above query into a transaction. As for MySQL version, I agree with @hsz - use the most current version possible.