如何在php中从mysql数据库获取最后一个insert id?

c7rzv4ha  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(387)

我想在插入之后从else语句中的表cart中获取最后一个insert id。但我没有得到身份证。请检查我的代码并指出我做错了什么:

// 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);
}

欢迎您的建议。

bzzcjhmw

bzzcjhmw1#

获取插入后的标识列值:

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
i7uq4tfw

i7uq4tfw2#

或在插入之前获取下一个自动增量值:

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

xxslljrj3#

而不是:

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

直接从文档中使用:

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

相关问题