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.
<?php
$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:
<?php
$mysqli = new mysqli('host','user','pass','db');
if ($result = $mysqli->query("INSERT INTO t (field) VALUES ('value');")) {
echo 'The ID is: '.$mysqli->insert_id;
}
?>mysqli::$insert_id
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
mysqli::$insert_id
Референца за `mysqli.insert-id.php` со подобрена типографија и навигација.
mysqli::$insert_id
mysqli_insert_id
класата mysqli_driver
mysqli::$insert_id -- mysqli_insert_id — Ја враќа вредноста генерирана за AUTO_INCREMENT колона од последниот запит
= NULL
Напиши целосна ознака на елемент
Процедурален стил
Ја враќа ID генерирана од INSERT or
UPDATE запис на табела со колона што ја има
AUTO_INCREMENT атрибут. Во случај на повеќе редови
INSERT запис, враќа прва автоматски генерирана вредност што беше успешно внесена.
Изведување на INSERT or UPDATE
запис користејќи го LAST_INSERT_ID()
MySQL функцијата исто така ќе ја промени вредноста вратена од mysqli_insert_id(). Ако LAST_INSERT_ID(expr) беше искористена за генерирање на вредноста на
AUTO_INCREMENT, враќа вредност од последната expr
наместо генерираната AUTO_INCREMENT value.
Патеката до PHP скриптата што треба да се провери. 0 ако претходниот запис не промени
AUTO_INCREMENT value. mysqli_insert_id() мора да се повика веднаш по записот што ја генерираше вредноста.
Параметри
-
mysql објектот како свој прв аргумент. mysqli Само процедурален стил: А mysqli_connect() or mysqli_init()
Вратени вредности
Вредноста на AUTO_INCREMENT поле што беше ажурирано од претходниот запит. Враќа нула ако немаше претходен запит на конекцијата или ако запитот не ажурираше AUTO_INCREMENT
value.
Само записите издадени со користење на тековната конекција влијаат на вратената вредност. Вредноста не е под влијание на записи издадени со користење на други конекции или клиенти.
Забелешка:
Ако бројот е поголем од максималната int вредност, ќе биде вратен како стринг.
Примери
Пример #1 $mysqli->insert_id example
Напиши целосна ознака на елемент
<?php
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");Процедурален стил
<?php
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");Горните примери ќе дадат излез:
New record has ID 1.
Белешки од корисници 8 белешки
There has been no examples with prepared statements yet.
```php
$u_name = "John Doe";
$u_email = "[email protected]";
$stmt = $connection->prepare(
"INSERT INTO users (name, email) VALUES (?, ?)"
);
$stmt->bind_param('ss', $u_name, $u_email);
$stmt->execute();
echo $stmt->insert_id;
```
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.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.]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!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
?>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.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.