【问题标题】:How to get last insert id from mysql database in php?如何在php中从mysql数据库中获取最后一个插入id?
【发布时间】:2018-08-24 17:10:32
【问题描述】:

我想在插入后的 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);
}

欢迎您提出建议。

【问题讨论】:

  • insert_id 是否自动递增?
  • 是mysqli? ($db) ?
  • $cart_id = 选择@@identity;我可以这样用吗?
  • 我在 localhost 中执行此操作。

标签: javascript php jquery mysql sql


【解决方案1】:

代替:

$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);

【讨论】:

  • 如何将最后一个插入 id 放入我的 $cart_id 中?就像 lastInsertId 是 71 然后 $cart_id =71;
  • @Sarah 更新代码,使用$cart_id = mysqli_insert_id($db);
  • $db->query("INSERT INTO cart (items,expire_date) VALUES ('{$items_json}','{$cart_expire}') ");mysqli_query($db, $query) ; $cart_id = mysqli_insert_id($db);不工作。
  • @Sarah 你没有使用我发布的代码。将原始代码中我的答案中的前 2 行替换为 3 行的第二个块。您仍在使用原始代码中的$db->query,这不在我的答案中。
  • 是的,代码现在可以工作,但是 else 语句仍然有效 如果 $cart_id =78; 我不知道 else 语句是如何工作的现在而不是空的。
【解决方案2】:

在插入后获取标识列值:

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

【讨论】:

  • 我没有选择 @@identity 如何使用它以及如何获取最后一个 id?
  • 这是在同一会话中插入之后的第二个查询。
  • @@identity 看起来更像是一个 SQL 服务器 (MSSQL) 变量
  • 没有,刚刚在 MySQL 5.5 中测试过
  • $cart_id = 选择@@identity;我可以这样使用它吗?如何将值选择标识放入 $cart_id?
【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 2023-03-14
    • 2015-03-20
    • 2010-12-13
    • 2011-06-01
    • 2011-03-06
    • 2010-12-07
    • 2014-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多