I have a table with 5 rows. Every time a user enters data into a form, it is entered into the table. My first column is called id
and holds the number of the post. What I want to do is get the value of id
from the previous row, add one to it and set it as the value in the current post's id
field. How do I do this?

- 8,820
- 20
- 54
- 84
-
3Is there a reason you are not using an `AUTO_INCREMENT` column? – lc. Mar 21 '13 at 10:49
-
Why not use auto-increment? – fcm Mar 21 '13 at 10:49
-
@lc. didn't know it existed. mysql noob here :/ – imulsion Mar 21 '13 at 13:20
6 Answers
Just set that field as primary key
and auto-increment
, it will automatically do this for you. You won't have to fetch the previous row
and add
that field value
to next one.

- 2,880
- 23
- 37
Set attribute auto increment
for "ID" field in the table that contains 5 columns.

- 76,500
- 11
- 62
- 80

- 4,275
- 1
- 19
- 26
You can use sql query like
"INSERT INTO my_table (id auto_increment,primary key(id))";
then you can get...
and eachtime you need not worry to insert id ,it will automatically increments

- 28,552
- 10
- 64
- 85
I would not recomend doing this as it could lead to a race condition.
Change the table structure and set the id
field to be the primary key
and set it to auto increment
. This way anytime a new row is added, it will auto-magically be assigned the next ID.
see this answer on details of how to set auto increment.
here is the query to alter your table and it will set your field or column as primary key and also auto increment it.
ALTER TABLE tbl ADD id INT PRIMARY KEY AUTO_INCREMENT;

- 99
- 2
- 10