How to get last inserted id in php PDO ?

<?php

$servername="localhost";
$username ="root";
$password="";

try{
    $connection=new PDO("mysql:host=$servername;dbname=test",$username,$password);
$connection->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$sql="insert into user (firstname,lastname,email,password) values ('kushal','khadka','kushalkhadkaa@gmail.com','password')";
//$connection->exec($sql);
if($connection->query($sql)==true){
echo 'you will have last inserted id';
// $last_id=$connection->insert_id;
// echo $last_id;
$stmt = $connection->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetch(PDO::FETCH_NUM);
$lastId = $lastId[0];
echo $lastId;
}
else{
    echo 'insertion failed';
}
echo 'inserted successfullly';
}
catch(PDOException $e){
echo "connection failed :".$e->getMessage();
}

?>

Share this

Related Posts

Previous
Next Post »