Search the MySQL manual:
MySQL Manual

Buy this Reference Manual in softcover from Barnes & Noble!

/ / Up / Table of Contents

8.4.3.126 mysql_insert_id()

my_ulonglong mysql_insert_id(MYSQL *mysql)

8.4.3.127 Описание

Возвращает идентификатор ID, сгенерированный для столбца AUTO_INCREMENT предыдущим запросом. Эту функцию следует использовать после выполнения запроса INSERT в таблице, содержащей поле AUTO_INCREMENT.

Следует учитывать, что функция mysql_insert_id() возвращает 0, если предыдущий запрос не сформировал величину AUTO_INCREMENT. Если необходимо сохранить эту величину в дальнейшем, то следует позаботиться о вызове функции mysql_insert_id() немедленно после запроса, который создает указанную величину.

Функция mysql_insert_id() обновляется после команд INSERT и UPDATE, которые генерируют величину AUTO_INCREMENT или устанавливают величину столбца в значение LAST_INSERT_ID(expr). See section 6.3.6.2 Разные функции.

Следует также иметь в виду, что величина SQL-функции LAST_INSERT_ID() всегда содержит самое последнее сгенерированное значение AUTO_INCREMENT и не обновляется между запросами, так как величина этой функции сохраняется сервером.

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

Величина поля AUTO_INCREMENT, обновленного предыдущим запросом. Возвращает нуль, если перед этим не было запроса в данном соединении или если данный запрос не обновил величину AUTO_INCREMENT.

8.4.3.129 Ошибки

Нет.

User Comments

Posted by Meir Michanie on Thursday August 22 2002, @2:20am [Delete] [Edit]

could someone add an example?

Posted by Juan Londono on Thursday December 19 2002, @3:33pm [Delete] [Edit]

For an example, just follow this link http://www.mysql.com/doc/en/Getting_unique_ID.html

Posted by on Wednesday December 18 2002, @5:27pm [Delete] [Edit]

A PHP example:

//This include opens de database
include '../../includes/db.php';

//Insert in first table
$result = mysql_query("INSERT INTO tblQuestions
(questionName)
VALUES ('$questionName')",$db);

//Insert in second table with ID of previous
insert
$result = mysql_query("INSERT INTO
tblQuestions_lng
(questionID,languageID,questionText)
VALUES (LAST_INSERT_ID
(),'$languageID','$questionText')",$db);

//Close database connection
mysql_close($db);

Posted by Mike Dierken on Friday November 15 2002, @2:00pm [Delete] [Edit]

What happens if another query that creates a row is
executed between the INSERT that creates the row
and the INSERT that uses LAST_INSERT_ID() ?

Is the LAST_INSERT_ID() relative only to the current
connection
or something? or is this situation a problem? and if
so, is there a solution?

Posted by Philippe A on Saturday February 1 2003, @8:01am [Delete] [Edit]

"The most recently generated ID is maintained in the server on a per-connection basis. It will not be changed by another client. It will not even be changed if you update another AUTO_INCREMENT column with a non-magic value (that is, a value that is not NULL and not 0). "

http://www.mysql.com/doc/en/Getting_unique_ID.html

Posted by [name withheld] on Thursday February 6 2003, @7:57am [Delete] [Edit]

mysql_insert_id(...) does not seem to work after an INSERT DELAYED. This is reasonable, as INSERT DELAYED does not block until the an autoincremented ID has been created (from a row insertion).

Add your own comment.

Top / / / Up / Table of Contents