10- MySQL Last Inserted

0
56

In our previous lesson, we tackle about how to insert a record in a MySQL database table. This time we’re going discuss MySQL Last Inserted to get the last Inserted ID from our table “tblpeople“. Using the AUTO_INCREMENT field, we are able to get the ID of last inserted or updated record immediately.

Since we will be using the same code that we use from our previous topic called “09-MySQL Insert” we only need to add a single line of code for retrieving and echo the Last Inserted ID.

MySQL Last Inserted

Example Using MySQLi(Object-Oriented):

  1. die("Connection failed: " . $conn->connect_error);
  2. }
  3.  
  4. // sql to Insert record table
  5. $sql = "INSERT INTO `tblpeople` (`LNAME`, `FNAME`, `ADDRESS`)
  6. VALUES ('Villanueva', 'Joken', 'Kabankalan City');";
  7.  
  8. if ($conn->query($sql) === TRUE) {
  9. $lastinsertedid = $conn->insert_id;
  10. echo "New record created successfully! And the last record inserted is:" . $lastinsertedid;
  11. } else {
  12. echo "Error: " . $sql . "
  13. " . $conn->error;
  14. }
  15.  
  16. $conn->close();
  17.  
  18. ?>

 

Example Using MySQLi(Procedural):

  1. $username = "root";
  2. $password = "";
  3. $database = "mysqltutorial";
  4.  
  5. // Create connection
  6. $conn = mysqli_connect($server, $username, $password, $database);
  7. // Check connection
  8. if (!$conn) {
  9. die("Connection failed: " . mysqli_connect_error());
  10. }
  11.  
  12. // sql to Insert record table
  13. $sql = "INSERT INTO `tblpeople` (`LNAME`, `FNAME`, `ADDRESS`)
  14. VALUES ('Villanueva', 'Joken', 'Kabankalan City');";
  15.  
  16. if (mysqli_query($conn, $sql)) {
  17. $lastinserteid = mysqli_insert_id($conn);
  18. echo "New record created successfully! And the last Inserted ID is : ". $lastinserteid;
  19. } else {
  20. echo "Error: " . $sql . "
  21. " . mysqli_error($conn);
  22. }
  23.  
  24. mysqli_close($conn);
  25. ?>

 

Example Using PDO:

  1. $sql = "INSERT INTO `tblpeople` (`LNAME`, `FNAME`, `ADDRESS`)
  2. VALUES ('Villanueva', 'Joken', 'Kabankalan City');";
  3.  
  4. // use exec() because no results are returned
  5. $conn->exec($sql);
  6. $lastinsertedid = $conn->lastInsertId();
  7. echo "New record created successfully! And the last Inserted ID is :" . $lastinsertedid;
  8. }
  9. catch(PDOException $e)
  10. {
  11. echo $sql . "
  12. " . $e->getMessage();
  13. }
  14.  
  15. $conn = null;
  16. ?>

Our previous Topic Called:09- MySQL Insert Query

Facebook Comments
(Visited 28 times, 1 visits today)

LEAVE A REPLY

Please enter your comment!
Please enter your name here