I'm trying to some something like that:
INSERT INTO dir_pictures SET filename=CONCAT(picture_id,'-test');
picture_id is my primary key, auto-increment. Basically I'm trying to put the id of this insert statement, in the statement itself.
I'm sure it can be done with some extra PHP code or using more than one statements, but I was wondering if there is a quick and easy way to do it in one shot.
PS. The statement above always put '0-test'
If you insert a record into a table that contains an AUTO_INCREMENT column, you can obtain the value stored into that column by calling the mysql_insert_id() function.
If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL.
You can also use INSERT ... TABLE in MySQL 8.0. 19 and later to insert rows from a single table. INSERT with an ON DUPLICATE KEY UPDATE clause enables existing rows to be updated if a row to be inserted would cause a duplicate value in a UNIQUE index or PRIMARY KEY .
The INSERT command is used to add new data into a table. MySql will add a new row, once the command is executed.
Insert a record first. Then separate your statements with a semicolon and use LAST_INSERT_ID() to fetch the newly inserted autoincrement id. Execute in one go.
insert into dir_pictures .... ; update dir_pictures set filename=CONCAT(LAST_INSERT_ID(),'-test') where id = LAST_INSERT_ID()
Just select the current auto_increment value for the table form the information_schema as part of your insert:
INSERT INTO dir_pictures SET filename=CONCAT((SELECT auto_increment FROM
information_schema.tables WHERE table_name='dir_pictures'), '-test')
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