-3

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?

imulsion
  • 8,820
  • 20
  • 54
  • 84

6 Answers6

8

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.

Dead Man
  • 2,880
  • 23
  • 37
2

The SQL query you need is:

SELECT max(id) 
FROM tableName;
Toon Casteele
  • 2,479
  • 15
  • 25
2

Set attribute auto increment for "ID" field in the table that contains 5 columns.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
Ravindra Shekhawat
  • 4,275
  • 1
  • 19
  • 26
1

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

GautamD31
  • 28,552
  • 10
  • 64
  • 85
1

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.

Community
  • 1
  • 1
Kami
  • 19,134
  • 4
  • 51
  • 63
0

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;
Devendra
  • 99
  • 2
  • 10