3

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?

Rogger Fernandes
  • 805
  • 4
  • 14
  • 28

2 Answers2

2

call lastInsertId of your PDO object.

$stmt->execute([':question' => $text]);
return $pdo->lastInsertId();
steven
  • 4,868
  • 2
  • 28
  • 58
-1

After just inserting the record in the database, write another query to fetch top record from the primary key column values in descending order.

e.g. select prim_key_id top 1 from table order by prim_key_id desc;

The_Amol
  • 309
  • 3
  • 15