Page 1 of 1

Get ID after insert with PDO

Posted: 20 Apr 2021, 12:33
by JanMolendijk
Hello Coursesweb,

I asking for longer time myself how to get the ID after an insert into database with pdo.

Code: Select all

<?php
if(isset($_POST["btnSubmit"])){
$hostname='127.0.0.1';
$username='paper_maker';
$password='123456';

$ip = $_SERVER['REMOTE_ADDR'];

$string=exec('getmac');
$mac_adres=substr($string, 0, 17); 

try {
$dbh = new PDO("mysql:host=$hostname;dbname=paper_maker",$username,$password);

$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "INSERT INTO tracker_comment (id_user,name_user,adres_note,comment,date_today)
VALUES ('".$_POST["id_user"]."','".$_POST["name_user"]."','".$_POST["adres_note"]."','".$_POST["comment"]."','".$_POST["date_today"]."')";
if ($dbh->query($sql)) {
echo "";
}
else{
echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>";
}

$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
?>

Get ID after insert with PDO

Posted: 20 Apr 2021, 15:45
by MarPlo
To get the id after an Insert with pdo, use the lastInsertId() method.

Code: Select all

$sql = "INSERT INTO tracker_comment (id_user,name_user,adres_note,comment,date_today)
VALUES ('".$_POST["id_user"]."','".$_POST["name_user"]."','".$_POST["adres_note"]."','".$_POST["comment"]."','".$_POST["date_today"]."')";
if ($dbh->query($sql)) {
  $last_id = $dbh->lastInsertId();  // contains the last id after this insert
  echo 'Last id inserted: '. $last_id;
}
else echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>";