how to get last insert id in php?

Today, We want to share with you how to get last insert id in php.In this post we will show you get last insert id in php mysqli, hear for how to get id from another table in php? we will give you demo and example for implement.In this post, we will learn about Laravel 5.8 – Get Last Inserted ID with an example.

PHP MySQL Get Last Inserted ID

In the table “allProducts”, the “id” column is an AUTO_INCREMENT field:

CREATE TABLE allProducts (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
product_name VARCHAR(30) NOT NULL,
product_desc VARCHAR(30) NOT NULL,
pcode VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)

Example (MySQLi Object-oriented)

connect_error) {
  die("Connection failed: " . $link_new->connect_error);
}

$query_s = "INSERT INTO allProducts (product_name, product_desc, pcode)
VALUES ('Jayshukh', 'Dhameliya', 'P00054')";

if ($link_new->query($query_s) === TRUE) {
  $last_id = $link_new->insert_id;
  echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
  echo "Error: " . $query_s . "
" . $link_new->error; } $link_new->close(); ?>

Example (MySQLi Procedural)

" . mysqli_error($link_new);
}

mysqli_close($link_new);
?>

Example (PDO)

setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $query_s = "INSERT INTO allProducts (product_name, product_desc, pcode)
  VALUES ('Jayshukh', 'Dhameliya', 'p0001')";

  $link_new->exec($query_s);
  $last_id = $link_new->lastInsertId();
  echo "New record created successfully. Last inserted ID is: " . $last_id;
} catch(PDOException $e) {
  echo $query_s . "
" . $e->getMessage(); } $link_new = null; ?>

I hope you get an idea about How to check whether an array is empty using PHP?.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment