Php5 mysql получить id
Содержание:
SQL Учебник
SQL ГлавнаяSQL ВведениеSQL СинтаксисSQL SELECTSQL SELECT DISTINCTSQL WHERESQL AND, OR, NOTSQL ORDER BYSQL INSERT INTOSQL Значение NullSQL Инструкция UPDATESQL Инструкция DELETESQL SELECT TOPSQL MIN() и MAX()SQL COUNT(), AVG() и …SQL Оператор LIKESQL ПодстановочныйSQL Оператор INSQL Оператор BETWEENSQL ПсевдонимыSQL JOINSQL JOIN ВнутриSQL JOIN СлеваSQL JOIN СправаSQL JOIN ПолноеSQL JOIN СамSQL Оператор UNIONSQL GROUP BYSQL HAVINGSQL Оператор ExistsSQL Операторы Any, AllSQL SELECT INTOSQL INSERT INTO SELECTSQL Инструкция CASESQL Функции NULLSQL ХранимаяSQL Комментарии
Technical Details
Return Value: | An integer that represents the value of the AUTO_INCREMENT field updated by the last query. Returns zero if there were no update or no AUTO_INCREMENT field |
---|---|
PHP Version: | 5+ |
Example — Procedural style
Assume that the «Persons» table has an auto-generated id field. Return the id
from the last query:
<?php
$con = mysqli_connect(«localhost»,»my_user»,»my_password»,»my_db»);if (mysqli_connect_errno()) {
echo «Failed to connect to MySQL: » . mysqli_connect_error();
exit();
}mysqli_query($con, «INSERT INTO Persons (FirstName, LastName, Age)
VALUES (‘Glenn’, ‘Quagmire’, 33)»);// Print auto-generated idecho «New record has id: » . mysqli_insert_id($con); mysqli_close($con);
?>
Example
Let’s look at some MySQL LAST_INSERT_ID function examples and explore how to use the LAST_INSERT_ID function in MySQL.
For example, if we had the following suppliers table with an AUTO_INCREMENT field called supplier_id:
CREATE TABLE suppliers ( supplier_id INT AUTO_INCREMENT NOT NULL PRIMARY KEY, supplier_name VARCHAR(50) NOT NULL, website VARCHAR(50) );
And the suppliers table contained the following records:
supplier_id | supplier_name | website |
---|---|---|
1 | Tech on the Net | www.techonthenet.com |
2 | Check Your Math | www.checkyourmath.com |
3 | Big Activities | www.bigactivities.com |
And we executed the following INSERT statement:
INSERT INTO suppliers (supplier_name, website) VALUES ('Oracle', 'www.oracle.com');
The suppliers table would now look like this:
supplier_id | supplier_name | website |
---|---|---|
1 | Tech on the Net | www.techonthenet.com |
2 | Check Your Math | www.checkyourmath.com |
3 | Big Activities | www.bigactivities.com |
4 | Oracle | www.oracle.com |
And if we executed the LAST_INSERT_ID function as follows:
mysql> SELECT LAST_INSERT_ID(); Result: 4
The LAST_INSERT_ID function would return 4 since the last INSERT statement inserted a record into the suppliers table with a supplier_id (ie: AUTO_INCREMENT value) of 4.
Affecting more than one AUTO_INCREMENT value
Let’s take a quick look at how the LAST_INSERT_ID function would behave if the most recent INSERT set more than one AUTO_INCREMENT value. In other words, what would happen if we inserted 2 records with our last INSERT statement.
Let’s look again at the suppliers table with an AUTO_INCREMENT field called supplier_id:
CREATE TABLE suppliers ( supplier_id INT AUTO_INCREMENT NOT NULL PRIMARY KEY, supplier_name VARCHAR(50) NOT NULL );
And the suppliers table contained the following records:
supplier_id | supplier_name | website |
---|---|---|
1 | Tech on the Net | www.techonthenet.com |
2 | Check Your Math | www.checkyourmath.com |
3 | Big Activities | www.bigactivities.com |
4 | Oracle | www.oracle.com |
We also have a customers table with the following records:
customer_id | customer_name |
---|---|
1 | HP |
2 | Samsung |
And we executed the following INSERT statement that uses a SELECT statement to insert more than one record into the suppliers table:
INSERT INTO suppliers (supplier_name) SELECT customer_name FROM customers ORDER BY customer_id;
After executing this INSERT statement, the suppliers table would now look like this:
supplier_id | supplier_name | website |
---|---|---|
1 | Tech on the Net | www.techonthenet.com |
2 | Check Your Math | www.checkyourmath.com |
3 | Big Activities | www.bigactivities.com |
4 | Oracle | www.oracle.com |
5 | HP | null |
6 | Samsung | null |
As you can see the INSERT statement inserted 2 new records into the suppliers table (supplier_id=5 and supplier_id=6).
Now when we execute the LAST_INSERT_ID function as follows:
mysql> SELECT LAST_INSERT_ID(); Result: 5
The LAST_INSERT_ID function would return 5 because the record with the supplier_id=5 was the first AUTO_INCREMENT value to be set by the most recent INSERT statement.
Пример
Рассмотрим примеры MySQL функции LAST_INSERT_ID, чтобы понять, как использовать функцию LAST_INSERT_ID в MySQL.
Например, если бы у нас была следующая таблица suppliers с AUTO_INCREMENT полем supplier_id:
MySQL
CREATE TABLE suppliers
( supplier_id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
supplier_name VARCHAR(50) NOT NULL,
website VARCHAR(50) );
1 2 3 4 |
CREATETABLEsuppliers (supplier_idINTAUTO_INCREMENTNOT NULLPRIMARY KEY, supplier_nameVARCHAR(50)NOT NULL, websiteVARCHAR(50)); |
И таблица suppliers содержала следующие записи:
supplier_id | supplier_name | website |
---|---|---|
1 | google_user | google.com |
2 | yandex_user | yandex.ru |
3 | mail_user | mail.ru |
И мы выполнили следующий оператор INSERT:
MySQL
INSERT INTO suppliers
(supplier_name, website)
VALUES
(‘Oracle_user’, ‘oracle.com’);
1 2 3 4 |
INSERTINTOsuppliers |
Таблица suppliers теперь выглядит так:
supplier_id | supplier_name | website |
---|---|---|
1 | google_user | google.com |
2 | yandex_user | yandex.ru |
3 | mail_user | mail.ru |
4 | Oracle_user | oracle.com |
И если мы выполним функцию LAST_INSERT_ID следующим образом:
MySQL
mysql> SELECT LAST_INSERT_ID();
4
1 2 |
mysql>SELECTLAST_INSERT_ID(); 4 |
Функция LAST_INSERT_ID вернет 4, поскольку последний оператор INSERT вставил запись в таблицу suppliers с supplier_id (то есть: значение AUTO_INCREMENT), равным 4.
Воздействие на несколько значений AUTO_INCREMENT
Рассмотрим, как будет вести себя функция LAST_INSERT_ID, если последний INSERT установит более одного значения AUTO_INCREMENT. Другими словами, что произойдет, если мы вставим 2 записи нашим последним оператором INSERT.
Давайте еще раз посмотрим на таблицу suppliers с AUTO_INCREMENT полем supplier_id:
MySQL
CREATE TABLE suppliers
( supplier_id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
supplier_name VARCHAR(50) NOT NULL );
1 2 3 |
CREATETABLEsuppliers (supplier_idINTAUTO_INCREMENTNOT NULLPRIMARY KEY, supplier_nameVARCHAR(50)NOT NULL); |
И таблица suppliers содержит следующие записи:
supplier_id | supplier_name | website |
---|---|---|
1 | google_user | google.com |
2 | yandex_user | yandex.ru |
3 | mail_user | mail.ru |
4 | Oracle_user | oracle.com |
У нас также есть таблица customers со следующими записями:
customer_id | customer_name |
---|---|
1 | HP |
2 | Samsung |
И мы выполним следующий оператор INSERT, который использует предложение SELECT для вставки более чем одной записи в таблицу suppliers:
MySQL
INSERT INTO suppliers
(supplier_name)
SELECT customer_name
FROM customers
ORDER BY customer_id;
1 2 3 4 5 |
INSERTINTOsuppliers SELECTcustomer_name FROMcustomers ORDER BYcustomer_id; |
После выполнения оператора INSERT таблица suppliers теперь будет выглядеть так:
supplier_id | supplier_name | website |
---|---|---|
1 | google_user | google.com |
2 | yandex_user | yandex.ru |
3 | mail_user | mail.ru |
4 | Oracle_user | oracle.com |
5 | HP | null |
6 | Samsung | null |
Как вы можете видеть, оператор INSERT вставил 2 новых записи в таблицу suppliers (supplier_id = 5 и supplier_id = 6).
Теперь, когда мы выполняем функцию LAST_INSERT_ID следующим образом:
MySQL
mysql> SELECT LAST_INSERT_ID();
#Результат: 5
1 2 3 |
mysql>SELECTLAST_INSERT_ID(); #Результат: 5 |
Функция LAST_INSERT_ID вернет 5, потому что запись с supplier_id = 5 была первым значением AUTO_INCREMENT, которое будет установлено самым последним оператором INSERT.