0

I am inserting new data into a MySQL and I have a column called "bookingid" that is the primary key and has auto increment. I need to get the number of the auto increment after inserting my data, here is my code:

    try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

   // prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO reservations (bookingdatetime, firstname, lastname, address) 
VALUES (:bookingdatetime, :firstname, :lastname, :address)");

$stmt->bindParam(':bookingdatetime', $bookingdatetime);
$stmt->bindParam(':firstname', $fname);
$stmt->bindParam(':lastname', $lname);
$stmt->bindParam(':address', $address);


// insert a row

$stmt->execute();

echo "success! row id: ";

}catch(PDOException $e){
echo json_encode(array("title" => "Database Error", "body" => $e->getMessage()));
}
$conn = null;

How do I echo the increment where it says "success! row id: "? thank you!

1 Answers1

0

You can use lastInsertId() to retrieve the last row that was inserted:

$stmt->execute();
echo "success! row id: $stmt->lastInsertId()";

Note that lastInsertId() must be called before commit() in a transaction, otherwise it will return 0.

Obsidian Age
  • 41,205
  • 10
  • 48
  • 71