The id column is auto increment. I want the "rank" column to have the same value as the newly generated auto increment value from the "id" column. (eg. say the next auto increment value is 999... I want the rank to equal this too)
Can I do this in one query? OR do I have to run an additional query to get the auto increment value before
$query = "INSERT INTO $table1(id,name,rank)
VALUES('','bob','999')";
Obtaining the value of column that uses AUTO_INCREMENT after an INSERT statement can be achieved in a number of different ways. To obtain the value immediately after an INSERT , use a SELECT query with the LAST_INSERT_ID() function.
Syntax for MySQLMySQL uses the AUTO_INCREMENT keyword to perform an auto-increment feature. By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record. VALUES ('Lars','Monsen'); The SQL statement above would insert a new record into the "Persons" table.
MySQL will automatically assign sequence numbers to the AUTO_INCREMENT column even if we insert NULL, 0 or No Value to the column in a table.
No. A primary key must be unique and that has to be 100% guaranteed, and NON NULL A primary key should be stable if ever possible and not change. So you don't have to, but it's a good choice since there is no other naturally unique data and you don't want to have enormous primary keys.
You can get actual auto_increment value in one insert using this query:
insert into tablename (name,rank) values ( 'bob',(SELECT AUTO_INCREMENT
FROM information_schema.tables
WHERE table_name = 'tablename'
AND table_schema = DATABASE( ) ) )
See more here - How to get the next auto-increment id in mysql
last_insert_id()
is only set AFTER the insert completes (successfully or not). If you try something like
INSERT INTO yourtable (id, dupe_id) VALUES (null, last_insert_id())
and hoping that dupe_id
gets the same ID that'll be assigned to id
, then... no, it won't. last_insert_id()
will return the ID creatd by whatever insert was run BEFORE this particular statement.
You'll have to do (basically):
INSERT ...;
UPDATE yourtable SET dupe_id=last_insert_id() WHERE id=last_insert_id();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With