9951 explained code solutions for 126 technologies


php-mysqlHow to get the last insert ID in PHP MySQL?


The last insert ID in PHP MySQL can be obtained using the mysqli_insert_id() function. This function returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute.

Example code

$conn = mysqli_connect("localhost", "username", "password", "database");
$sql = "INSERT INTO table (column1, column2, column3) VALUES ('value1', 'value2', 'value3')";
$result = mysqli_query($conn, $sql);
$last_id = mysqli_insert_id($conn);
echo "Last insert ID is: " . $last_id;

Output example

Last insert ID is: 5

Code explanation

  • mysqli_connect(): Establishes a connection to a MySQL server.
  • mysqli_query(): Executes a query against the database.
  • mysqli_insert_id(): Returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute.

Helpful links

Edit this code on GitHub