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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?