我想在插入后从我的else语句中的表购物车中获取最后一个插入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);
}
欢迎您提出建议。
答案 0 :(得分:0)
在插入后获取标识列值:
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
答案 1 :(得分:0)
代替:
$db->query("INSERT INTO cart (items,expire_date) VALUES ('{$items_json}','{$cart_expire}') ");
$cart_id = $db->insert_id; // Here is the problem
直接在documentation中使用它:
$query = "INSERT INTO cart (items,expire_date) VALUES ('{$items_json}','{$cart_expire}') ";
mysqli_query($db, $query);
$cart_id = mysqli_insert_id($db);
答案 2 :(得分:0)
或者在插入之前获取下一个自动增量值:
$query = $db->query("SHOW TABLE STATUS LIKE 'cart'");
$next = $query->fetch(PDO::FETCH_ASSOC);
echo $next['Auto_increment'];