← Back to PHP Course | Chapter 11: Database | Lesson 13 of 21

PHP MySQL Get Last ID

एक auto-incrementing primary key वाला नया row insert करने के ठीक बाद, आपको अक्सर exactly यह जानना होता है कि MySQL ने अभी इसे कौन सी ID assign की -- उस record के page पर redirect करने के लिए, इसे किसी दूसरे table में एक related row से link करने के लिए, या बस इसे user को confirm करने के लिए। mysqli_insert_id() exactly वह value return करता है।
Syntax
php
mysqli_query($conn, "INSERT INTO table_name (column1) VALUES ('value')");
$id = mysqli_insert_id($conn);   // AUTO_INCREMENT id of the new row

एक नए Inserted Row की ID पाना

एक AUTO_INCREMENT primary key वाली किसी table में एक successful INSERT के तुरंत बाद, mysqli_insert_id($conn) exactly वह ID value return करता है जो MySQL ने उस नए row के लिए generate की -- किसी अलग SELECT query की ज़रूरत नहीं।

उदाहरण: Getting the ID of a Newly Inserted Row

php
<?php
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE orders (id INTEGER PRIMARY KEY AUTOINCREMENT, item TEXT)");
$db->exec("INSERT INTO orders (item) VALUES ('Book')");
echo $db->lastInsertRowID(); // mysqli_insert_id($conn) in MySQL
?>

नई ID का इस्तेमाल एक Related Row Insert करने में

एक बहुत common pattern है एक parent row (जैसे एक order) insert करना, mysqli_insert_id() से इसकी नई ID capture करना, और फिर उस ID को तुरंत related child rows (जैसे order items) insert करने के लिए इस्तेमाल करना जो एक foreign key के through इसे reference करते हैं।

उदाहरण: Using the New ID to Insert a Related Row

php
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE orders (id INTEGER PRIMARY KEY AUTOINCREMENT)");
$db->exec("CREATE TABLE items (order_id INTEGER, product TEXT)");
$db->exec("INSERT INTO orders DEFAULT VALUES");
// Declare `$orderId`, set to `$db->lastInsertRowID()`
$orderId = $db->lastInsertRowID();
$db->exec("INSERT INTO items (order_id, product) VALUES ($orderId, 'Pen')");
// Print "Linked item to order #$orderId" to the output
echo "Linked item to order #$orderId";
?>

mysqli_insert_id() कब 0 Return करता है

mysqli_insert_id() 0 return करता है अगर सबसे हाल की query किसी auto-increment column में एक INSERT नहीं थी -- जैसे एक UPDATE, एक SELECT, या बिल्कुल कोई auto-increment primary key न वाली किसी table में एक insert -- जो check करना उचित है अगर आपका code मानता है कि हमेशा एक ID generate हुई है।

उदाहरण: When mysqli_insert_id() Returns 0

php
<?php
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)");
$db->exec("INSERT INTO users (name) VALUES ('Alice')");
$db->exec("UPDATE users SET name = 'Alicia' WHERE id = 1");
echo $db->lastInsertRowID(); // still 1 in SQLite, but mysqli_insert_id() returns 0 after a non-insert query
?>

इसके बजाय PDO से Last ID पाना

PDO, PHP का दूसरा database abstraction layer, $pdo->lastInsertId() के through equivalent functionality देता है, same तरीके से call किया गया -- relevant insert के तुरंत बाद, same PDO connection object पर।

उदाहरण: Getting the Last ID with PDO Instead

php
<?php
// Create a new `PDO` instance with 'sqlite::memory:', stored in `$pdo`
$pdo = new PDO('sqlite::memory:');
$pdo->exec("CREATE TABLE orders (id INTEGER PRIMARY KEY AUTOINCREMENT, item TEXT)");
$pdo->exec("INSERT INTO orders (item) VALUES ('Book')");
// Print `$pdo->lastInsertId()` to the output
echo $pdo->lastInsertId();
?>

नई ID के Common Uses

related rows link करने से आगे, नई inserted ID अक्सर user को अभी बनाए गए record के लिए एक detail page पर redirect करने के लिए इस्तेमाल होती है (जैसे /orders/42), एक confirmation message बनाने के लिए, या एक successful create operation के बाद एक JSON API response के हिस्से की तरह ID return करने के लिए।

उदाहरण: Common Uses for the New ID

php
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE orders (id INTEGER PRIMARY KEY AUTOINCREMENT, item TEXT)");
$db->exec("INSERT INTO orders (item) VALUES ('Book')");
// Declare `$id`, set to `$db->lastInsertRowID()`
$id = $db->lastInsertRowID();
// Print `json_encode(["status" => "created", "order_id" => $id])` to the output
echo json_encode(["status" => "created", "order_id" => $id]);
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. दूसरी queries चल चुकने के काफी बाद mysqli_insert_id() call करना, जबकि यह सिर्फ उसी connection पर सबसे हाल के successful insert की ID reliably reflect करता है।
  2. यह मान लेना कि mysqli_insert_id() बिना किसी AUTO_INCREMENT column वाली tables के लिए काम करता है -- इसकी meaningful value सिर्फ ऐसे column में inserts के लिए है।
  3. mysqli_insert_id() को कई concurrent connections वाले context में इस्तेमाल करना और उम्मीद करना कि यह किसी तरह किसी दूसरे connection की last insert ID return कर देगा।
चैप्टर सारांश
  • mysqli_insert_id($conn) उस specific connection पर सबसे हाल के INSERT से generate हुई auto-increment ID return करता है।
  • इसे उसी connection पर कोई और query चलने से पहले, relevant INSERT के तुरंत बाद call किया जाना चाहिए।
  • अगर last query ने कोई नई auto-increment value generate नहीं की तो यह 0 return करता है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.