PHP Get ID of Last Inserted Record

PHP Get ID of Last Inserted Record

Welcome to the In Pakainfo.com website! You will Step By Step learn web programming, easy and very fun. This website allmost provides you with a complete web programming tutorial presented in an easy-to-follow manner. Each web programming tutorial has all the practical examples with web programming script and screenshots available.PHP Get ID of Last Inserted Record

With MySQLi Object-oriented: Return last insert ID in mySQL using PHP

$last_id = $conn->insert_id;

With PDO:

$pdo->lastInsertId();

With Mysqli:

$mysqli->insert_id;

MySQLi Object-oriented – Get Last ID (Get ID of The Last Inserted Record)

$sqlQuery = "INSERT INTO products (productname, productdesc, status)
VALUES ('Rolex', 'Rolex watch', '123')";

//get Last Inserted Record ID
if ($conn->query($sqlQuery) === TRUE) {
    $last_id = $conn->insert_id;
    echo "Your New record created successfully. your Last inserted ID is: " . $last_id;
} else {
    echo "Error: " . $sqlQuery . "
" . $conn->error; }

Get last inserted record ID from mysql using php

$query = "INSERT into products VALUES('', '".$productname."')";
 $data_query_result = mysql_query($query) or die(mysql_error());
 $new_row_id = mysql_insert_id($data_query_result);
 echo "
";
 echo $new_row_id;
 echo "

";
//$new_row_id holds last inserted id print

Getting the last INSERTed record from Mysql

 int mysql_insert_id (resource [link_identifier])  

MySQL LAST_INSERT_ID example
create table

CREATE TABLE products (
    pid INT AUTO_INCREMENT PRIMARY KEY,
    pdescription VARCHAR(250) NOT NULL
)

insert a new row into the products table

INSERT INTO products(pdescription)
VALUES('MySQL last_insert_id');

LAST_INSERT_ID

SELECT LAST_INSERT_ID();

MySQLi Procedural – Get Last ID (Get ID of The Last Inserted Record)

$conn = mysqli_connect($servername, $username, $password, $dbname);

$sqlQuery = "INSERT INTO products (productname, productdesc, status)
VALUES ('Rolex', 'Rolex watch', '123')";

//get Last Inserted Record ID
if (mysqli_query($conn, $sqlQuery)) {
    $last_id = mysqli_insert_id($conn);
    echo "Your New record created successfully. your Last inserted ID is: " . $last_id;
} else {
    echo "Error: " . $sqlQuery . "
" . mysqli_error($conn); }

PDO – Get Last ID (Get ID of The Last Inserted Record)

$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sqlQuery = "INSERT INTO products (productname, productdesc, status)
VALUES ('Rolex', 'Rolex watch', '123')";

//get Last Inserted Record ID
	$conn->exec($sqlQuery);
    $last_id = $conn->lastInsertId();
    echo "Your New record created successfully. your Last inserted ID is: " . $last_id;

mysql_query('INSERT INTO products(a) VALUES(\'b\')');
$id = mysql_insert_id();

Demo Example

Leave a Comment