简体   繁体   中英

How to get last insert id from mysql database in php?

I want to get last insert id from my table cart in my else statement after the insert. But I am not getting the id. Please check my code and suggest what am I doing wrong:

// Check to see if the cart COOKIE exists
if ($cart_id != '') {
// Here I want to update but not getting $cart_id, so everytime insert query fire in else statement

}else{

$items_json = json_encode($item);
$cart_expire = date("Y-m-d H:i:s",strtotime("+30 days"));
$db->query("INSERT INTO cart (items,expire_date) VALUES ('{$items_json}','{$cart_expire}') ");
$cart_id = $db->insert_id; // Here is the problem
setcookie(CART_COOKIE,$cart_id,CART_COOKIE_EXPIRE,'/',$domain,false);
}

Your suggestions would be welcome.

Get the identity column value AFTER the insert:

create table student (
  id int primary key not null auto_increment,
  name varchar(20)
);

insert into student (name) values ('John');

select @@identity; -- returns 1

insert into student (name) values ('Peter');

select @@identity; -- returns 2

Instead of:

$db->query("INSERT INTO cart (items,expire_date) VALUES ('{$items_json}','{$cart_expire}') ");
$cart_id = $db->insert_id; // Here is the problem

Use this, directly from the documentation :

$query = "INSERT INTO cart (items,expire_date) VALUES ('{$items_json}','{$cart_expire}') ";
mysqli_query($db, $query);
$cart_id = mysqli_insert_id($db);

Or get the next auto incremental value before insert:

$query = $db->query("SHOW TABLE STATUS LIKE 'cart'");
$next = $query->fetch(PDO::FETCH_ASSOC);
echo $next['Auto_increment'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM