[英]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. 我想在插入后从我的else语句中的表购物车中获取最后一个插入ID。 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'];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.