【问题标题】:How to get auto-increment Primary key of inserted row PDO PHP?如何获取插入行 PDO PHP 的自动增量主键?
【发布时间】:2015-05-19 16:54:52
【问题描述】:

我想在 PHP 中使用 PDO 向数据库中插入一个新行,主键是自动递增的,所以我没有插入 PK 的值。这是代码:

public function insertQuestion($text){
    try{
        $sql = "INSERT INTO question(text) VALUES(:question)"; 

        $stm = $this->prepare($sql);

        $stm->execute(array(
                ':question' => $text,
        ));

        $question = new Question();
        $question->text = $text;
        $question->id = -1; // How do I get the PK of the row just inserted?

    }catch(PDOException $e){
        if ($e->getCode() == 1062) return FALSE; // fails unique constraint
        else echo $e->getMessage();
    }   
}

但是,我需要存储插入到 $question 对象的新行的 PK,我还有其他唯一的属性,所以我可以执行 SELECT 语句来查找 PK,但是,有没有更好的方法干吗?

【问题讨论】:

标签: php sql sqlite pdo


【解决方案1】:

只在数据库中插入记录后,编写另一个查询,从主键列值中按降序获取顶部记录。

例如select prim_key_id top 1 from table order by prim_key_id desc;

【讨论】:

  • 并希望您没有并发用户插入问题
  • 是的,这可能是考虑因素之一;)
【解决方案2】:

调用您的 PDO 对象的 lastInsertId。

if($stmt->execute()) {
    return $pdo->lastInsertId();
}
return false;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    • 1970-01-01
    • 2014-06-05
    • 1970-01-01
    • 2011-07-07
    • 2012-02-22
    相关资源
    最近更新 更多