Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 675
John Avatar asked Jan 09 '10 13:01

John


2 Answers

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.

like image 67
Chris Tonkinson Avatar answered Oct 06 '22 00:10

Chris Tonkinson


If you are talking about primary key then set id column as primary and auto_increment.

Increasing field is looking like that:

UPDATE table SET field = field + 1 WHERE id = 9

About MySQL version - use the newest you can. ;)
> 5.0 will be fine.

like image 42
hsz Avatar answered Oct 06 '22 01:10

hsz