php mysql last insert id

mysqli::$insert_id

Описание

Список параметров

Возвращаемые значения

Только запросы, выданные с использованием текущего соединения, влияют на возвращаемое значение. На значение не влияют запросы, выданные с использованием других подключений или клиентов.

Если число больше максимального значения целого числа, функция вернёт строку.

Примеры

Результат выполнения данных примеров:

User Contributed Notes 8 notes

I have received many statements that the insert_id property has a bug because it «works sometimes». Keep in mind that when using the OOP approach, the actual instantiation of the mysqli class will hold the insert_id.

There has been no examples with prepared statements yet.

«`php
$u_name = «John Doe»;
$u_email = «johndoe@example.com»;

For UPDATE you simply change query string and binding parameters accordingly, the rest stays the same.

Of course the table needs to have AUTOINCREMENT PRIMARY KEY.

[EDIT by danbrown AT php DOT net: This is another prime example of the limits of 32-bit signed integers.]

When running extended inserts on a table with an AUTO_INCREMENT field, the value of mysqli_insert_id() will equal the value of the *first* row inserted, not the last, as you might expect.

query(«INSERT INTO mytable (field1,field2,field3) VALUES (‘val1′,’val2′,’val3’),
(‘val1′,’val2′,’val3’),
(‘val1′,’val2′,’val3’)»);

The example is lack of insert_id in multi_query. Here is my example:
Assuming you have a new test_db in mysql like this:

create database if not exists test_db;
use test_db;
create table user_info (_id serial, name varchar(100) not null);
create table house_info (_id serial, address varchar(100) not null);

Then you run a php file like this:

last insert id in query is 1
last insert id in first multi_query is 4
last insert id in second multi_query is 1

Conclusion:
1 insert_id works in multi_query
2 insert_id is the first id mysql has used if you have insert multi values

msqli_insert_id();
This seems to return that last id entered.
BUT, if you have multiple users running the same code, depending on the server or processor I have seen it return the wrong id.

Test Case:
Two users added an item to their list.
I have had a few times where the id was the id from the other user.
This is very very rare and it only happens on my test server and not my main server.

I am guessing it is because of multicores (maybe hyperthreading) or how the operating system handles multi-threads.

Источник

mysql_insert_id

mysql_insert_id — Возвращает идентификатор, сгенерированный при последнем INSERT-запросе

Данный модуль устарел, начиная с версии PHP 5.5.0, и удалён в PHP 7.0.0. Используйте вместо него MySQLi или PDO_MySQL. Смотрите также инструкцию MySQL: выбор API. Альтернативы для данной функции:

Описание

Возвращает идентификатор, сгенерированный колонкой с AUTO_INCREMENT последним запросом (обычно INSERT).

Список параметров

Возвращаемые значения

Примеры

Пример #1 Пример использования mysql_insert_id()

Примечания

mysql_insert_id() конвертирует возвращаемый функцией MySQL C API тип значения функции mysql_insert_id() в тип long (называемый int в PHP). Если ваша колонка AUTO_INCREMENT имеет тип BIGINT (64 бита), то значение, возвращаемое функцией в результате преобразования может быть искажено. Используйте вместо данной функции внутреннюю MySQL-функцию LAST_INSERT_ID() в SQL-запросе. Подробнее о максимальных значениях целых чисел смотрите в разделе документации, посвящённом целым числам.

Так как mysql_insert_id() работает с последним выполненным запросом, вызывайте mysql_insert_id() сразу же после запроса, генерирующего новое значение.

Значение в SQL функции MySQL LAST_INSERT_ID() всегда содержит последний сгенерированный ID и не обнуляется между запросами.

Смотрите также

User Contributed Notes 12 notes

There’s nothing inherently wrong with using auto-increment fields. There’s also nothing wrong with the main competetive idea, which is for the database to supply a primitive sequence of non-repeating identifiers, typically integers. This is rather like which side of the road you drive on.

The bigger problem is when people don’t understand what they are doing with database access. It’s like driving a car without really knowing the rules of the road. Such people wind up making bad decisions without realizing it, and then, eventually, something breaks.

Databases are complex beasts, and worth taking the time to really understand. Learn about the implications and limitations of different approaches to solving problems. Then, you will be prepared to pick a solution based on what has to work.

I thought this would be relevant to all the people using mysqli and looking for the ID after INSERT command :

>
?>

Then, on the other side, let us call this function as follows :

I don’t get all the fuss around this.

I read:
«The value of mysql_insert_id() is affected only by statements issued within the current client connection. It is not affected by statements issued by other clients.»

I can’t really see what’s inaccurate about that.

«In the case of a multiple-row INSERT statement, mysql_insert_id() returns the first automatically generated AUTO_INCREMENT value; if no such value is generated, it returns the last last explicit value inserted into the AUTO_INCREMENT column.»

I must be missing something here but why would you insert multiple rows and then only handle the last one with some favoured behaviour? You could just as well insert them one at a time and then handle each row separately with the latest id.

I can’t see what’s wrong with that.

However I can see what’s wrong with simply using max(my_table.id_column) because of the concurrent access issues this would imply.

Forget about using MAX to get the last inserted id. Race conditions like other users inserting between your SELECT MAX(.. and your INSERT may render your id unusable.

The WAY to get the id is by using mysql_insert_id() or the mysql SQL function LAST_INSERT_ID().

Take care, if using mysql_insert_id() you should provide the resource returned by the mysql_connect, not the resultset returned by mysql_query.

How to get ID of the last updated row in MySQL?

75
down vote
I’ve found an answer to this problem 🙂

SET @update_id := 0;
UPDATE some_table SET row = ‘value’, @update_id := id)
WHERE some_other_row = ‘blah’ LIMIT 1;
SELECT @update_id;
EDIT by aefxx

This technique can be further expanded to retrieve the ID of every row affected by an update statement:

SET @uids := null;
UPDATE footable
SET foo = ‘bar’
WHERE fooid > 5
AND ( SELECT @uids := CONCAT_WS(‘,’, fooid, @uids) );
SELECT @uids;
This will return a string with all the IDs concatenated by a colon.

Источник

How to get last inserted id from table MySQL [duplicate]

I am running 1 script in php for that I need last inserted id in subscription table. By using that id I want to make notification note for that subscription.

I am getting 0 instead of real last inserted value.

6 Answers 6

If you use php to connect to mysql you can use mysql_insert_id() to point to last inserted id.

php mysql last insert id. Смотреть фото php mysql last insert id. Смотреть картинку php mysql last insert id. Картинка про php mysql last insert id. Фото php mysql last insert id

LAST_INSERT_ID() returns the last id from a previous insert statement. If you want the most recently inserted record and are using Auto Increment Prime keys, you can use the code below:

If you need to know what the NEXT id will be, you can get this from INFORMATION_SCHEMA

php mysql last insert id. Смотреть фото php mysql last insert id. Смотреть картинку php mysql last insert id. Картинка про php mysql last insert id. Фото php mysql last insert id

This question has already been answered many times: MySQL: LAST_INSERT_ID() returns 0

You are using that function out of context. It will only work if you inserted a row immediately prior thusly:

You can however select the row with the highest id, which logically would be the most recently added.

The standard approach however is to simply call mysqli_insert_id or mysql_insert_id (depending on whether you are using the mysqli or mysql PHP library. I should add that the mysql library is very inadvisable to use since it is almost completely deprecated). Here’s what the whole thing would ideally look like:

If however you didn’t insert a subscription in the same script as collecting the most recent row ID, use the ‘select max’ approach. This seems unlikely given that you mentioned ‘1 script’

Also, if your ID’s are non-consecutive, or you do not have an ID field, or you have row ID’s higher than the one you just added you should probably consider a ‘date_added’ column to determine which one was really the latest. These scenarios are rather unlikely however.

Источник

LAST_INSERT_ID() MySQL

I have a MySQL question that I think must be quite easy. I need to return the LAST INSERTED ID from table1 when I run the following MySql query:

As you can understand the current code will just return the LAST INSERT ID of table2 instead of table1, how can I get the id from table1 even if I insert into table2 between?

14 Answers 14

You could store the last insert id in a variable :

Or get the max id from table1 (EDIT: Warning. See note in comments from Rob Starling about possible errors from race conditions when using the max id)

(Warning: as Rob Starling points out in the

Since you actually stored the previous LAST_INSERT_ID() into the second table, you can get it from there:

This enables you to insert a row into 2 different tables and creates a reference to both tables too.

php mysql last insert id. Смотреть фото php mysql last insert id. Смотреть картинку php mysql last insert id. Картинка про php mysql last insert id. Фото php mysql last insert id

I had the same problem in bash and i’m doing something like this:

which works fine:-) But

don’t work. Because after the first command, the shell will be logged out from mysql and logged in again for the second command, and then the variable @last_insert_id isn’t set anymore. My solution is:

Maybe someone is searching for a solution an bash 🙂

We only have one person entering records, so I execute the following query immediately following the insert:

This retrieves the last id from the database.

It would be possible to save the last_id_in_table1 variable into a php variable to use it later?

With this last_id I need to attach some records in another table with this last_id, so I need:

1) Do an INSERT and get the last_id_in_table1

2) For any indeterminated rows in another table, UPDATING these rows with the last_id_insert generated in the insert.

Instead of this LAST_INSERT_ID() try to use this one

php mysql last insert id. Смотреть фото php mysql last insert id. Смотреть картинку php mysql last insert id. Картинка про php mysql last insert id. Фото php mysql last insert id

php mysql last insert id. Смотреть фото php mysql last insert id. Смотреть картинку php mysql last insert id. Картинка про php mysql last insert id. Фото php mysql last insert id

For no InnoDB solution: you can use a procedure don’t forgot to set the delimiter for storing the procedure with ;

And you can use it.

In trigger BEFORE_INSERT this working for me:

Or in simple select:

If you want, remove the comment /*-1*/ and test in other cases. For multiple use, I can write a function. It’s easy.

php mysql last insert id. Смотреть фото php mysql last insert id. Смотреть картинку php mysql last insert id. Картинка про php mysql last insert id. Фото php mysql last insert id

A mi no me funciona mi codigo. alguna idea para recuperar el id de mi ultimo insert este es mi codigo soy nuevo desarrollando y no conozco mucho

YA VERIFIQUE Y ESTA CORRECTA LA CONEXION Y LOS CAMPOS DE LA BASE DE DATOS.

For last and second last:

php mysql last insert id. Смотреть фото php mysql last insert id. Смотреть картинку php mysql last insert id. Картинка про php mysql last insert id. Фото php mysql last insert id

Just to add for Rodrigo post, instead of LAST_INSERT_ID() in query you can use SELECT MAX(id) FROM table1;, but you must use (),

If you need to have from mysql, after your query, the last auto-incremental id without another query, put in your code:

Источник

Особенности работы LAST_INSERT_ID() и AUTO_INCREMENT в MySQL

Причина по которому я написал эту статью — это неожиданное поведение ф-ции LAST_INSERT_ID() при выполнении запроса в котором я в поле с атрибутом AUTO_INCREMENT передавал значение.

LAST_INSERT_ID()

И так имеем таблички

Добавляем данные, обратите внимание на запросы тут :

Ну разница не только в значениях полей, а тут главная фишка, что при добавлении автора в первой тройке запросов, автоинкремент делал сама БД, а во второй тройке я принудительно указал номер в поле автоикремент, вот что получилось:

Как вы заметили, с таблицей авторов все окей, 1 и 5 запись добавились с теми номерами ключей которые указала БД и я соот.
Во второй таблице — книги, все хуже. У книг с ИД 1 и 2 ИД_автора все ок, привязаны к автору с ИД1 в таблице авторов, а вот книги с ИД 3 и 4 привязаны к автору ИД которого в таблице авторов просто нет?!

Почему произошла такая ситуация. Разбираем.

Оказывается эта функция LAST_INSERT_ID() возвращает ИД поля с атрибутом автоинкремент если запись была вставлена успешно и автоинкремент работал. Что у нас и было в первой тройке запросов, а вот во второй тройке запросов увы такого не было, т.к. я указал ИД, а значение 2 взялось, т.к. последний успешный запрос был при добавлении второй книги первого автора!

Какие еще приколы скрывает в себе эта функция, оказывается если вы делаете многократное добавление в рамках одного запроса, то ф-ция LAST_INSERT_ID() выдаст ИД только первой успешно добавленной записи. Пруфлинк.

А если сделать так

Век живи — век учись (© Народная мудрость).

В заключении еще решил разобрать поведение атрибута AUTO_INCREMENT.

AUTO_INCREMENT

Это такой атрибут который генерирует порядковый номер к указанному полю. Полей должно быть только с типом integer или float (TINYINT, SMALLINT, MEDIUMINT, INT, BIGINT, FLOAT) и имеющий индекс типа (UNIQUE, PRIMARY, KEY). Причем у каждого из типа поля есть свой предел автоинкремента, например для поля TINYINT это значение 127 или 255 для TINYINT UNSIGNED и тд смотрите документацию. Каждая последующая запись будет +1 (по-дефолту) к максимальному числу до добавления в этом поле, наверное не так лучше сказать.
В MySQL есть вспомогательная БД information_schema в которой хранится необходимая информация о всех таблицах всех БД сервера. И вот именно там храниться следующий номер для автоинкремента, т.е. перед добавление записи в таблицу БД не ищет максимальный номер записи, на это ведь будет тратиться время, которое дорого.
В таблице может быть только одно поле которое имеет автоинкремент, и причем это поле не должно иметь дефолтного значения.
Если мы хотим указать какой-то свой номер для поля с автоинкрементом, то мы должны просто передать этому полю значение. Если значение уже есть в таблице, то будет ошибка если тип индекса в поле UNIQUE или PRIMARY, но есть тип индекса KEY то запись спокойно добавится.
Если по каким-то причинам нам надо указывать поле с автоинкрементом в запросе, но мы хотим чтобы этому полю было присвоено значение автоинкремента автоматом, то в это поле надо передать 0 (ноль) или NULL:

Если по каким-то причинам вы хотите добавить значение 0 в поля автоинкремента, для этого необходимо прописать в файле-настроке (my.ini / my.cnf) следующую строчку

но делать это не рекомендуется, т.к. если сделать дамп БД и потом развернуть его на другом сервере, где нет такой настройки, то данные будут искажены.

Если по каким-то причинам вам необходимо сделать чтобы следующая запись начиналась с какого-нибудь друго числа, просто напишите команду:

не забывайте об используемом типе поля, чтобы ваше число не вышло за рамки.

А например возникла задача делать автоинкремент не ++1 а через 5, т.е. 1,6,11 т.д. как быть в таком?
Для этого имеются две переменные auto_increment_increment и auto_increment_offset. auto_increment_increment — указывает шаг приращения, а auto_increment_offset указывает стартовую точку.
Для просмотра что у вас используется команда, которая показывает как у вас настроен автоинкремент:

Поменять можно 2 путями — только на время работы сервера БД (до перезагрузки) и навсегда — смена конфигурационного файла

Более детальней об изменении AUTO_INCREMENT читать тут.

Обнаружил в интернете интересный сайт с подкастами. Советую скачать podcast, подкасты на различные темы.Также советую послушать подкасты на сайте dev.mysql.com по тематике данной статьи.

Статья просмотренна 228921 раз, зашло посетителей 68551

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *