PHP Function Reference

PHP mysqli_stmt $insert_id Property



The PHP mysqli_stmt::$insert_id / mysqli_stmt_insert_id() function is used to get the ID generated from the previous INSERT operation.

Syntax

//Object-oriented style
$mysqli_stmt->insert_id;

//Procedural style
mysqli_stmt_insert_id(statement)

Parameters

statement Required. For procedural style only: Specify a mysqli_stmt object returned by mysqli_stmt_init().

Return Value

Returns the ID generated from the previous INSERT operation.

Example: Object-oriented style

The example below shows the usage of mysqli_stmt::insert_id property.

<?php
//establishing connection to the database
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
  echo "Failed to connect to MySQL: ". $mysqli->connect_error;
  exit();
}

//preparing an SQL statement for execution
$query = "INSERT INTO Employee (Name, City, Salary) VALUES (?, ?, ?)";
$stmt = $mysqli->prepare($query);
$name = "John";
$city = "London";
$salary = 2800;
$stmt->bind_param('ssd', $name, $city, $salary);

//executing the SQL statement
$stmt->execute();

//getting the ID
$id = $stmt->insert_id;

printf("New record has ID %d.\n", $id);

//closing the connection
$mysqli->close();
?>

The output of the above code will be similar to:

New record has ID 1.

Example: Procedural style

The example below shows the usage of mysqli_stmt_insert_id() function.

<?php
//establishing connection to the database
$mysqli = mysqli_connect("localhost", "user", "password", "database");
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: ". mysqli_connect_error();
  exit();
}

//preparing an SQL statement for execution
$query = "INSERT INTO Employee (Name, City, Salary) VALUES (?, ?, ?)";
$stmt = mysqli_prepare($mysqli, $query);
$name = "John";
$city = "London";
$salary = 2800;
mysqli_stmt_bind_param($stmt, 'ssd', $name, $city, $salary);

//executing the SQL statement
mysqli_stmt_execute($stmt);

//getting the ID
$id = mysqli_stmt_insert_id($stmt);

printf("New record has ID %d.\n", $id);

//closing the connection
mysqli_close($mysqli);
?>

The output of the above code will be similar to:

New record has ID 1.

❮ PHP MySQLi Reference