我想在插入后在 else 语句中从表购物车中获取最后的插入 ID。但我没有得到 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);
}
欢迎您提出建议。
最佳答案
而不是:
$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);
关于javascript - 如何在php中从mysql数据库获取最后插入的id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52009033/