Php id после insert

PHP MySQL Get Last Inserted ID

If we perform an INSERT or UPDATE on a table with an AUTO_INCREMENT field, we can get the ID of the last inserted/updated record immediately.

In the table «MyGuests», the «id» column is an AUTO_INCREMENT field:

CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)

The following examples are equal to the examples from the previous page (PHP Insert Data Into MySQL), except that we have added one single line of code to retrieve the ID of the last inserted record. We also echo the last inserted ID:

Example (MySQLi Object-oriented)

$servername = «localhost»;
$username = «username»;
$password = «password»;
$dbname = «myDB»;

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) die(«Connection failed: » . $conn->connect_error);
>

$sql = «INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘John’, ‘Doe’, ‘john@example.com’)»;

if ($conn->query($sql) === TRUE) $last_id = $conn->insert_id;
echo «New record created successfully. Last inserted ID is: » . $last_id;
> else echo «Error: » . $sql . «
» . $conn->error;
>

Example (MySQLi Procedural)

$servername = «localhost»;
$username = «username»;
$password = «password»;
$dbname = «myDB»;

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) die(«Connection failed: » . mysqli_connect_error());
>

$sql = «INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘John’, ‘Doe’, ‘john@example.com’)»;

if (mysqli_query($conn, $sql)) $last_id = mysqli_insert_id($conn);
echo «New record created successfully. Last inserted ID is: » . $last_id;
> else echo «Error: » . $sql . «
» . mysqli_error($conn);
>

Example (PDO)

$servername = «localhost»;
$username = «username»;
$password = «password»;
$dbname = «myDBPDO»;

try $conn = new PDO(«mysql:host=$servername;dbname=$dbname», $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = «INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘John’, ‘Doe’, ‘john@example.com’)»;
// use exec() because no results are returned
$conn->exec($sql);
$last_id = $conn->lastInsertId();
echo «New record created successfully. Last inserted ID is: » . $last_id;
> catch(PDOException $e) echo $sql . «
» . $e->getMessage();
>

Источник

mysqli_insert_id

Returns the ID generated by an INSERT or UPDATE query on a table with a column having the AUTO_INCREMENT attribute. In the case of a multiple-row INSERT statement, it returns the first automatically generated value that was successfully inserted.

Performing an INSERT or UPDATE statement using the LAST_INSERT_ID() MySQL function will also modify the value returned by mysqli_insert_id() . If LAST_INSERT_ID(expr) was used to generate the value of AUTO_INCREMENT , it returns the value of the last expr instead of the generated AUTO_INCREMENT value.

Returns 0 if the previous statement did not change an AUTO_INCREMENT value. mysqli_insert_id() must be called immediately after the statement that generated the value.

Читайте также:  Php функция возвращает несколько значений

Parameters

Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

Return Values

The value of the AUTO_INCREMENT field that was updated by the previous query. Returns zero if there was no previous query on the connection or if the query did not update an AUTO_INCREMENT value.

Only statements issued using the current connection affect the return value. The value is not affected by statements issued using other connections or clients.

Note:

If the number is greater than the maximum int value, it will be returned as a string.

Examples

Example #1 $mysqli->insert_id example

mysqli_report ( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
$mysqli = new mysqli ( «localhost» , «my_user» , «my_password» , «world» );

$mysqli -> query ( «CREATE TABLE myCity LIKE City» );

$query = «INSERT INTO myCity VALUES (NULL, ‘Stuttgart’, ‘DEU’, ‘Stuttgart’, 617000)» ;
$mysqli -> query ( $query );

printf ( «New record has ID %d.\n» , $mysqli -> insert_id );

/* drop table */
$mysqli -> query ( «DROP TABLE myCity» );

mysqli_report ( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
$link = mysqli_connect ( «localhost» , «my_user» , «my_password» , «world» );

mysqli_query ( $link , «CREATE TABLE myCity LIKE City» );

$query = «INSERT INTO myCity VALUES (NULL, ‘Stuttgart’, ‘DEU’, ‘Stuttgart’, 617000)» ;
mysqli_query ( $link , $query );

printf ( «New record has ID %d.\n» , mysqli_insert_id ( $link ));

/* drop table */
mysqli_query ( $link , «DROP TABLE myCity» );

The above examples will output:

User Contributed Notes 10 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.

The following code will return nothing.
$mysqli = new mysqli ( ‘host’ , ‘user’ , ‘pass’ , ‘db’ );
if ( $result = $mysqli -> query ( «INSERT INTO t (field) VALUES (‘value’);» )) echo ‘The ID is: ‘ . $result -> insert_id ;
>
?>

This is because the insert_id property doesn’t belong to the result, but rather the actual mysqli class. This would work:

$mysqli = new mysqli ( ‘host’ , ‘user’ , ‘pass’ , ‘db’ );
if ( $result = $mysqli -> query ( «INSERT INTO t (field) VALUES (‘value’);» )) echo ‘The ID is: ‘ . $mysqli -> insert_id ;
>
?>

There has been no examples with prepared statements yet.

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

$stmt = $connection->prepare(
«INSERT INTO users (name, email) VALUES (?, ?)»
);
$stmt->bind_param(‘ss’, $u_name, $u_email);
$stmt->execute();

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.

When using «INSERT . ON DUPLICATE KEY UPDATE `id` = LAST_INSERT_ID(`id`)», the AUTO_INCREMENT will increase in an InnoDB table, but not in a MyISAM table.

Watch out for the oo-style use of $db->insert_id. When the insert_id exceeds 2^31 (2147483648) fetching the insert id renders a wrong, too large number. You better use the procedural mysqli_insert_id( $db ) instead.

[EDIT by danbrown AT php DOT net: This is another prime example of the limits of 32-bit signed integers.]
Читайте также:  Java base64 decode online

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.

//mytable has an auto_increment field
$db->query(«INSERT INTO mytable (field1,field2,field3) VALUES (‘val1′,’val2′,’val3’),
(‘val1′,’val2′,’val3’),
(‘val1′,’val2′,’val3’)»);

echo $db->insert_id; //will echo the id of the FIRST row inserted
?>

If you try to INSERT a row using ON DUPLICATE KEY UPDATE, be aware that insert_id will not update if the ON DUPLICATE KEY UPDATE clause was triggered.

When you think about it, it’s actually very logical since ON DUPLICATE KEY UPDATE is an UPDATE statement, and not an INSERT.

In a worst case scenario, if you’re iterating over something and doing INSERTs while relying on insert_id in later code, you could be pointing at the wrong row on iterations where ON DUPLICATE KEY UPDATE is triggered!

What is unclear is how concurrency control affects this function. When you make two successive calls to mysql where the result of the second depends on the first, another user may have done an insert in the meantime.

The documentation is silent on this, so I always determine the value of an auto increment before and after an insert to guard against this.

I was having problems with getting the inserted id, and did a bit of testing. It ended up that if you commit a transaction before getting the last inserted id, it returns 0 every time, but if you get the last inserted id before committing the transaction, you get the correct value.

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:

define ( ‘SERVER’ , ‘127.0.01’ );
define ( ‘MYSQL_USER’ , ‘your_user_name’ );
define ( ‘MYSQL_PASSWORD’ , ‘your_password’ );

$db = new mysqli ( SERVER , MYSQL_USER , MYSQL_PASSWORD , «test_db» , 3306 );
if ( $db -> connect_errno )
echo «create db failed, error is » , $db -> connect_error ;
else $sql = «insert into user_info »
. «(name) values »
. «(‘owen’), (‘john’), (‘lily’)» ;
if (! $result = $db -> query ( $sql ))
echo «insert failed, error: » , $db -> error ;
else
echo «last insert id in query is » , $db -> insert_id , «\n» ;
$sql = «insert into user_info»
. «(name) values »
. «(‘jim’);» ;
$sql .= «insert into house_info »
. «(address) values »
. «(‘shenyang’)» ;
if (! $db -> multi_query ( $sql ))
echo «insert failed in multi_query, error: » , $db -> error ;
else echo «last insert id in first multi_query is » , $db -> insert_id , «\n» ;
if ( $db -> more_results () && $db -> next_result ())
echo «last insert id in second multi_query is » , $db -> insert_id , «\n» ;
else
echo «insert failed in multi_query, second query error is » , $db -> error ;
>
$db -> close ();
>
?>

Читайте также:  Очистка содержимого файла php

You will get output 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.

It is rare, but it happens.

Источник

mysql_insert_id

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

Описание

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

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

Соединение MySQL. Если идентификатор соединения не был указан, используется последнее соединение, открытое mysql_connect() . Если такое соединение не было найдено, функция попытается создать таковое, как если бы mysql_connect() была вызвана без параметров. Если соединение не было найдено и не смогло быть создано, генерируется ошибка уровня E_WARNING .

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

Идентификатор, сгенерированный колонкой с AUTO_INCREMENT последним запросом в случае успеха , 0, если последний запрос не генерирует значение AUTO_INCREMENT value, и FALSE , если соединение MySQL не было установлено.

Примеры

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

$link = mysql_connect ( ‘localhost’ , ‘mysql_user’ , ‘mysql_password’ );
if (! $link ) die( ‘Ошибка соединения: ‘ . mysql_error ());
>
mysql_select_db ( ‘mydb’ );

mysql_query ( «INSERT INTO mytable (product) values (‘kossu’)» );
printf ( «Идентификатор последней вставленной записи %d\n» , 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 и не обнуляется между запросами.

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

Источник

Оцените статью