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?
call lastInsertId of your PDO object.
if($stmt->execute()) {
return $pdo->lastInsertId();
}
return false;
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;