douzhou7124 2015-03-17 09:58
浏览 151
已采纳

如何获得自动递增插入行PDO PHP的主键?

I want to insert a new row to a database using PDO in PHP, the primary key is auto-increment, so I am not inserting the value of the PK. This is the code:

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();
    }   
}

But, I need to store the PK of the new row inserted to the $question object, I have other attributes that are UNIQUE, so I could do a SELECT statement to find the PK, however, is there a better approach for doing it?

  • 写回答

2条回答 默认 最新

  • douzhe1264 2015-03-17 10:03
    关注

    call lastInsertId of your PDO object.

    if($stmt->execute()) {
        return $pdo->lastInsertId();
    }
    return false;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料