【问题标题】:Getting insert id with insert PDO MySQL使用插入 PDO MySQL 获取插入 ID
【发布时间】:2011-04-14 03:23:53
【问题描述】:

我正在掌握 PDO 的基础知识。

但是我试图获取插入行的 id,我使用的是:

$query = $system->db->prepare("INSERT INTO {$this->_table} (name,description) VALUES (:name,:description)");
$query->execute(array('name'=>$name,'description'=>$description));

我遇到的教程是关于交易的,但是我没有使用交易!

【问题讨论】:

    标签: php sql pdo


    【解决方案1】:

    使用交易时要注意。

    如果你在调用commit 之后调用lastInsertedIdlastInsertedId 将返回 0 而不是 id。 在execute 之后、commit 之前调用lastInsertedId

    $this->db->beginTransaction();
    $this->stmt->execute();
    $id = $this->db->lastInsertId();
    $this->db->commit();
    

    【讨论】:

      【解决方案2】:

      您可能正在寻找lastInsertId。 "返回最后插入的行或序列值的 ID"。

      $insertedId = $system->db->lastInsertId() ;
      

      【讨论】:

      • 啊哈谢谢!出于某种原因,我试图在 $query 变量上调用它。
      猜你喜欢
      • 1970-01-01
      • 2011-08-21
      • 2014-12-11
      • 2012-05-27
      • 2012-05-31
      • 2011-06-30
      相关资源
      最近更新 更多