So I've got a PHP page that inserts a booking into my database, and I am using the method lastInsertId()
to present the user with their Booking ID (which is set to AUTO_INCREMENT
in the database).
The problem is, two duplicate records are being added when the code runs, and the method is returning the second Booking ID. Can someone shed some light on why this is happening?
This is the code:
<?php
...
$stmt = $conn->prepare('INSERT bookings (DateFrom, DateTo, GuestHouseID_FK, GuestID_FK, RoomID_FK) VALUES (:DateFrom, :DateTo, :GuestHouseID_FK, :GuestID_FK, :RoomID_FK)');
$stmt->bindParam(':DateFrom', $DateFrom, PDO::PARAM_STR);
$stmt->bindParam(':DateTo', $DateTo, PDO::PARAM_STR);
$stmt->bindParam(':GuestHouseID_FK', $GuestHouseID_FK, PDO::PARAM_INT);
$stmt->bindParam(':GuestID_FK', $GuestID_FK, PDO::PARAM_STR);
$stmt->bindParam(':RoomID_FK', $RoomID_FK, PDO::PARAM_STR);
$stmt->execute();
echo '<H3>';
echo 'Thank you. Your booking has been completed!';
echo '</H3>';
if($stmt->execute()){
$booking_id = $conn->lastInsertId();
echo "Your Booking ID is " . $booking_id;
echo '<hr>';
}
echo '<p>Click here to return to the main menu</p>';
echo '<form action="@AT2_main_menu.html">';
echo '<input type="submit" value="Main menu">';
echo '</form>';
}
catch(PDOException $e)
{
echo "Something's gone wrong. Please try again or contact the admin";
}
$conn = null;
?>