php mysqli 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.

Источник

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 mysqli last insert id. Смотреть фото php mysqli last insert id. Смотреть картинку php mysqli last insert id. Картинка про php mysqli last insert id. Фото php mysqli 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 mysqli last insert id. Смотреть фото php mysqli last insert id. Смотреть картинку php mysqli last insert id. Картинка про php mysqli last insert id. Фото php mysqli 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.

Источник

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 do I get the last inserted ID of a MySQL table in PHP?

I have a table into which new data is frequently inserted. I need to get the very last ID of the table. How can I do this?

17 Answers 17

If you’re still using Mysql:

there is a function to know what was the last id inserted in the current connection

plus using max is a bad idea because it could lead to problems if your code is used at same time in two different sessions.

That function is called mysql_insert_id

It’s ok. Also you can use LAST_INSERT_ID()

Try this should work fine:

To get last inserted id in codeigniter After executing insert query just use one function called insert_id() on database, it will return last inserted id

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

You can get the latest inserted id by the in built php function mysql_insert_id();

you an also get the latest id by

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

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

NOTE: if you do multiple inserts with one statement mysqli::insert_id will not be correct.

create table xyz (id int(11) auto_increment, name varchar(255), primary key(id));

insert into xyz (name) values(‘one’),(‘two’),(‘three’);

The mysqli::insert_id will be 1 not 3.

To get the correct value do:

This has been document but it is a bit obscure.

Источник

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

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

Описание

Возвращает идентификатор, сгенерированный колонкой с 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 и не обнуляется между запросами.

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

Источник

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

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