开发者

Insert into database with unique/primary key

I'm using a simple form to insert posts to my MySQL database, I want each post to have an unique ID but don't know the proper way to do it.

I already created a column named "PID" and set it as a primary key however I don't know how to make each INSERT generate the PID. The only way I can think of is to make PHP look for the higher PID and add +1 to it. Is there an easier way to do it?开发者_运维技巧 Thanks


If you manage your MySQL database with a software like e.g. phpMyAdmin then you can set the "auto_increment" flag on this column.

Else you have to set it manually as described in this manual.


You need to set PID to be an Identity field

http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html

 CREATE TABLE posts(
 PID MEDIUMINT NOT NULL AUTO_INCREMENT,
 someotherfield CHAR(30) NOT NULL,
 ...etc...,
 PRIMARY KEY (PID)
 )


You can make the field 'auto_increment'. That way, MySQL creates a unique id for each record. You can use mysql_insert_id to get the last inserted id.


Make the PID column auto_increment


Set that PID field to AUTO_INCREMENT. In PHPMyAdmin there's a INDEX field you can set to AI, if I remember correctly.

Using AUTO_INCREMENT


Use auto_increment on the field.

E.g. pid int primary key auto_increment


You can use auto increment on Id field.


Make the field auto_increment in your mysql table.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜