Запрос последнего id php

mysql_insert_id

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

Описание

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

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

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.

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.

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.

I thought this would be relevant to all the people using mysqli and looking for the ID after INSERT command :

function insert_join ( $catid , $disc_id ) // insert a new item into the database
$conn = db_connect ();
// insert new item
$demande = «insert into categories_disc values (», ‘» . $catid . «‘, ‘» . $disc_id . «‘)» ;
$resultat = $conn -> query ( $demande );
if (! $resultat ) return false ;
> else return $conn -> insert_id ; // function will now return the ID instead of true.
>

>
?>

Then, on the other side, let us call this function as follows :

$cat_id = insert_join ( $catid , $disc_id );
if( $cat_id !== false )

echo «

Category stuff was added to the database as follows :
» ;
echo «


ID de la category : » . $cat_id . «


» ;

Take care of setting an empty value for the AUTO_INCREMENT Field else you never get a value except zero returned from mysq_insert_id() .

Источник

ID последней записи в базе данных MySQL в PHP

Обычно, задача узнать последний добавленный идентификатор (id) возникает после запроса вставки данных INSERT. Причем, поле, которое будет содержать это значение, назначается автоматически базой данных.

Автоматическое назначение id в базе данных используется очень часто. При этом сразу решается проблема уникальности идентификатора – он не будет дублироваться, и не нужно реализовывать специальный код для его генерации. Тем более что любая СУБД обязательно включает в себя такой функционал.

Стоит уточнить, что иногда есть необходимость генерировать идентификатор по другим правилам. Такое делается либо для удобства дальнейшей работы – например, включение в id значения, которые будет иметь какой-то смысл – текущая дата или тип записи. Либо, наоборот, идентификатор формируется набором случайных символов для обеспечения безопасности. В этом случае, сложно будет его случайно указать или угадать.

Для нахождения последнего id, созданного при вставке дынных в MySQL, в PHP используется функция mysql_insert_id. Обязательных параметров у нее нет, поэтому в коде просто присваиваем значение, возвращаемое этой функции в переменную или сразу используем ее в качестве параметра в другой функции.

$last_id = mysql_insert_id(); // запись значения в переменную
my_function(mysql_insert_id()); // указание параметром в другую функцию

В разработке, такой подход наиболее простой и удобный. Но применять его нужно, зная, что эта функция возвращает идентификатор, созданный для любой из таблиц последним. Т.е. может возникнуть ситуация, когда в «один момент времени» в БД будет добавлено две записи. При этом функция mysql_insert_id будет возвращать id записи, добавленной последней.

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

Обычно этой функцией пользуются непосредственно после выполнения запроса на добавление данных, поэтому вероятность описанной ситуации сводится к минимуму. Но если известно, что этот механизм может многократно выполняться в единый момент времени, стоит вспомнить об этой проблеме и проверить насколько корректно все работает.

Источник

PHP MySQLi Get Last ID

We have various methods for selecting the last insertion id from the MySQL table.
1. We can select a single row from the table in descending order and store the id.
2. Select Maximum value.

If we INSERT or UPDATE a row on a SQL table with AUTO_INCREMENT field, we can get the ID of the last inserted or updated record from table.

We have a table «Users» like the one below and we insert another row in it, then we get the last ID from DataBase.

ID First Name Last Name UserName Email
1 Clark Kent clarkkent clarkkent@mail.com
2 John Carter johncarter johncarter@mail.com
3 Peter Parker peterparker peterparker@mail.com

PHP Get Last ID — MySQLi (object oriented)

Before accessing data from the MySQL database, we must be able to connect to the server.

For this example we’ll use the same Users table that we’ve created in the PHP MySQL create tables, which has three rows and five columns as: id, first_name, last_name, user_name and email, where id is the primary key column and marked with AUTO_INCREMENT flag.

$server_name = "localhost";
$user_name = "my_username";
$password = "my_password";
$db_name = "my_DB";

// Create connection
$link = new mysqli($server_name, $user_name,
$password, $db_name);

// Check connection
if ($link->connect_error) die("Connection failed: " . $link->connect_error);
>

$sql = "INSERT INTO Users (first_name, last_name, user_name, email)
VALUES ('Stwart', 'Martin', 'StwartM', 'StwartM@agernic.com')";


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

$link->close();
?>

Tags: How do I get the last inserted ID of a MySQL table in PHP?
How do I get the last row inserted id in MySQL?
How can I get last insert ID in PDO?
How can I get the last updated ID in PHP?
How do I find the last ID in MySQL?
How can I get my last ID?
PHP MySQLi last: insert id, error, last_insert_id, id, query, update id, row, get last insert id, get last query, php mysqli_query last insert id
PHP MySQLi get: last insert id, data, all rows, first row, get error, number of rows, single row, single value, field namess

PHP Get Last ID — MySQLi (Procedural)

How do I get the last row inserted id in MySQL? Example using MySQLi (Procedural)

$server_name = "localhost";
$user_name = "my_username";
$password = "my_password";
$db_name = "my_DB";

// Create connection
$link = mysqli_connect($server_name, $user_name,
$password, $db_name);

// Check connection
if (!$link) die("Connection failed: " . mysqli_connect_error());
>

$sql = "INSERT INTO Members (first_name, last_name, user_name, email)
VALUES ('Stwart', 'Martin', 'StwartM', 'StwartM@agernic.com')";

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

mysqli_close($link);

?>

PHP Get Last ID — MySQLi (PDO) extension

The following example insert another row and get the last ID from table named «Users» in database my_DB using PDO

$server_name = "localhost";
$user_name = "my_username";
$password = "my_password";
$db_name = "my_DB";

try $link = new PDO("mysql:host=$server_name;dbname=$db_name",
$user_name, $password);
// set the PDO error mode to exception
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = "INSERT INTO Members (first_name, last_name, user_name, email)
VALUES ('Stwart', 'Martin', 'StwartM', 'StwartM@agernic.com'";
// use exec() because no results are returned
$link->exec($sql);
$last_id = $conn->lastInsertId();
echo "New record created successfully. Last inserted ID is: " . $last_id;
> catch(PDOException $e) echo $sql . "
" . $e->getMessage();
>

$link = null;

?>

How do I find the last ID in MySQL?
How can I get my last ID?
PHP MySQLi last: insert id, error, last_insert_id, id, query, update id, row, get last insert id, get last query, php mysqli_query last insert id
PHP MySQLi get: last insert id, data, all rows, first row, get error, number of rows, single row, single value, field namess

PHP MySQLi Get Last ID — php tutorial

news templates

news templates

This tool makes it easy to create, adjust, and experiment with custom colors for the web.

news templates

Magnews2 is a modern and creative free magazine and news website template that will help you kick off your online project in style.

news templates

Find here examples of creative and unique website layouts.

news templates

Find here examples of creative and unique website CSS HTML menu.

Источник

Читайте также:  Regex all characters python
Оцените статью