I
I
Ivan Melnikov2018-03-24 07:49:55
MySQL
Ivan Melnikov, 2018-03-24 07:49:55

How can an application writing to a MySQL 5.7 database table get back the value of an auto-incrementing primary key?

MySQL 5.7 has a table:

CREATE TABLE user(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(30) NOT NULL,
PRIMARY KEY(id)
);

When writing in the name field, the id field will be filled in by the DBMS.
Some application has INSERT rights on the name field of this table. But it's not enough for this application to simply write to the table, it also needs to get back the value of the id field for the record it just made. How to implement it?
Records to the table can be made by different applications in parallel. Therefore, simply returning the maximum value from the id field will not work.
I have a collective farm idea on how to implement this, but for now I will keep silent about it.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Tsvetkov, 2018-03-24
@yellow79

Last_insert_id () is said to return the ID of the last inserted record within the current connection. That is, it will always return what you need, even though you have many applications that write to the database

O
Oleg, 2018-03-24
@402d

the application to use the regular functionality of the database driver
In PHP, for example, there is such a function
mixed mysqli_insert_id ( mysqli $link )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question