【问题标题】:Why does PDO::lastInsertId return 0?为什么 PDO::lastInsertId 返回 0?
【发布时间】:2011-07-02 18:40:19
【问题描述】:

这是我的代码。

// insert reward into wallet
$sql = "
INSERT INTO `wallet` (`uid`, `created_at`, `amount`, `type`, `payment_id`) VALUES (:uid, CURRENT_TIMESTAMP, :amount, 'payment', :payment_id);
";
$sth = self::link()->prepare($sql); 
// primary key makes sure payment does not get double rewarded
$sth->execute(
    array(
    ':uid' => $referer,
    ':amount' => $reward,
    ':payment_id' => $payment_data['payment_id'],
    )
);
var_dump(self::link()->errorInfo());
self::log("issuing subscription",self::LOG_LEVEL_DEBUG);
// extend referers subscription
$tid = self::link()->lastInsertId();
var_dump(self::link()->errorInfo());
self::log("using $tid as id for wallet transfer",self::LOG_LEVEL_DEBUG);

我的日志说:

[2011-07-02 20:31:44] using 0 as id for wallet transfer

然而插入查询成功,数据库记录被创建并且两个errorInfo输出都没有错误。

【问题讨论】:

  • 您的表中有任何 auto_increment 字段吗?当表中存在 auto_increment 字段时,lastInsertId 有效
  • 您也不需要在查询中使用分号...它绝对不需要,我什至可能使查询失败。你确定成功了吗?
  • 你成功了,谢谢。如果您可以将其发布为答案,那么我可以投票并接受。
  • 我确定我成功了,但感谢您指出这一点,将删除它
  • @prodigitalson:请添加您的评论作为答案,以便它可以被接受。

标签: php mysql pdo lastinsertid


【解决方案1】:

从您的查询中删除分号或分号后的空格或两者:

$sql = "
INSERT INTO `wallet` (`uid`, `created_at`, `amount`, `type`, `payment_id`) VALUES (:uid, CURRENT_TIMESTAMP, :amount, 'payment', :payment_id)
";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-31
    • 1970-01-01
    • 2022-12-19
    • 2021-12-27
    • 2012-09-27
    • 2020-10-30
    相关资源
    最近更新 更多