PHP MySQLi Get Last Insert ID 🎯

beginner
12 min

PHP MySQLi Get Last Insert ID 🎯

Welcome to this comprehensive guide on using PHP MySQLi to get the last inserted ID! In this lesson, we'll learn how to fetch the ID of the most recently inserted record, making it easier to manage your database operations. πŸ“ Note: This tutorial is designed for beginners and intermediates, so we'll be explaining the concepts from the ground up.

What is the Last Insert ID? πŸ“

When you insert a new record into a MySQL database, the database assigns a unique ID to that record. The LAST_INSERT_ID() function in MySQL allows you to retrieve the ID of the most recently inserted row.

Setting Up the Environment πŸ’‘ Pro Tip:

Before we dive into the PHP code, make sure you have the following prerequisites:

  1. A local server (e.g., XAMPP, WAMP, or MAMP) installed on your computer
  2. A MySQL database created and a table with the required columns
  3. PHP installed and the necessary libraries enabled

Connecting to the Database πŸ’‘ Pro Tip:

First, we'll establish a connection to our MySQL database using the PHP MySQLi extension.

php
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "database_name"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } ?>

Replace username, password, and database_name with your actual credentials.

Inserting a New Record πŸ“ Note:

Next, let's insert a new record into our table. We'll also store the last inserted ID for later use.

php
// SQL query to insert a new record $sql = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')"; // Execute the query if ($conn->query($sql) === TRUE) { // Get the last inserted ID $last_id = $conn->insert_id; echo "New record created successfully. Last inserted ID: $last_id"; } else { echo "Error: " . $sql . "<br>" . $conn->error; }

Make sure to replace table_name, column1, column2, value1, and value2 with your actual table name, columns, and values.

Retrieving the Last Insert ID πŸ’‘ Pro Tip:

Now that we've inserted a new record, let's fetch the last inserted ID using the $conn->insert_id property.

php
// Close the database connection $conn->close(); // Example usage of last inserted ID echo "The last inserted ID was: " . $last_id;

And that's it! You've now learned how to use PHP MySQLi to get the last inserted ID in a MySQL database. βœ…

Quick Quiz
Question 1 of 1

Which PHP MySQLi function is used to retrieve the last inserted ID?