【问题标题】:lastInsertId() not working on a PDO object, in an insert operation [closed]lastInsertId() 在插入操作中不适用于 PDO 对象[关闭]
【发布时间】:2013-05-16 15:18:51
【问题描述】:

我使用以下选项初始化类:

$options = array(
      PDO::ATTR_PERSISTENT => true, 
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);

那我就这样了

$this->sql = trim($sql);
$this->bind = $this->cleanup($bind);
$this->error = "";

try {
   $pdostmt = $this->prepare($this->sql);
   if($pdostmt->execute($this->bind) !== false) {
       if(preg_match("/^(" . implode("|", array("select", "describe", "pragma")) . ") /i", $this->sql))
           return $pdostmt->fetchAll(PDO::FETCH_ASSOC);
       elseif(preg_match("/^(" . implode("|", array("delete", "update")) . ") /i", $this->sql))
           return $pdostmt->rowCount();
       elseif(preg_match("/^(" . implode("|", array("insert")) . ") /i", $this->sql))
           return $pdostmt->lastInsertId();
}

那是因为在 INSERT 之后我需要返回最后插入的 id。 但有人告诉我 lastInsertId() 不是函数。 所以它不起作用。

有什么想法吗?也许错误的选择? 谢谢

【问题讨论】:

  • 这是面向对象的。为什么要把每一点信息都塞进一个函数中?为什么不只在需要 rowCount 时才调用 rowCount,并单独调用?
  • 你是对的,我从在线图书馆获得了代码,我只在 insert 中对其进行了修改,只是因为需要。当我有更多时间更新它,让它更苗条时,我会这样做;)无论如何,谢谢你的通知!

标签: php sql pdo last-insert-id


【解决方案1】:

它在 PDO 对象中,而不是在 PDOStatement 中。

http://php.net/manual/en/pdo.lastinsertid.php

【讨论】:

  • 是的,我注意到了....太愚蠢了...对不起,长时间的工作让你失明......谢谢
猜你喜欢
  • 2012-11-24
  • 2012-09-16
  • 1970-01-01
  • 2014-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多