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

巧了我就是萌 提交于 2019-11-28 21:03:36

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.

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.

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

--> The type of table depends on what you have planned for your application. It could be Innodb or Myisam. I suggest you to use numeric column so that you can increment/decrement them. Do NOT make it UNSIGNED if you plan to allow negative numbers.

Here's the limits that you might find useful in declaring your column length:

TINYINT (length)  - 1 - Integer with unsigned range of 0-255 and a signed range from -128-127
SMALLINT (length)  - 2 - Integer with unsigned range of 0-65535 and a signed range from -32768-32767
MEDIUMINT(length)  - 3 -  Integer with unsigned range of 0-16777215 and a signed range from -8388608-8388607
INT(length)   - 4 - Integer with unsigned range of 0-429467295 and a signed range from -2147483648-2147483647
BIGINT(length)   - 8 -  Integer with unsigned range of 0-18446744 and a signed range from
-9223372036854775808-9223372036854775807

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

--> Just to use auto-increment? You are well off using an up to date version. I suggest something > 5.2.4, if it's possible.

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

--> Sorry, don't have an answer for this at the moment.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!