Current Location: Home> Function Categories> mysqli::$insert_id

mysqli::$insert_id

(mysqli_insert_id) Returns the automatically generated id used in the latest query
Name:mysqli::$insert_id
Category:MySQLi
Programming Language:php
One-line Description:Returns the ID that was automatically generated in the last query.

Definition and usage

The mysqli_insert_id() function returns the id generated by the last query (generated using AUTO_INCREMENT).

Example

Example 1 - Object-Oriented Style

Suppose the "Persons" table has an automatically generated id field. Return the id of the last query:

 <?php
$mysqli = new mysqli ( "localhost" , "my_user" , "my_password" , "my_db" ) ;

if ( $mysqli -> connect_errno ) {
  echo "Failed to connect to MySQL: " . $mysqli -> connect_error ;
  exit ( ) ;
}

$mysqli -> query ( "INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Glenn', 'Quagmire', 33)" ) ;

// Print the automatically generated id
echo "New record has id: " . $mysqli -> insert_id ;

$mysqli -> close ( ) ;
?>

Example 2 - Procedural Style

Suppose the "Persons" table has an automatically generated id field. Return the id of the last query:

 <?php
$con = mysqli_connect ( "localhost" , "my_user" , "my_password" , "my_db" ) ;

if ( mysqli_connect_errno ( ) ) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error ( ) ;
  exit ( ) ;
}

mysqli_query ( $con , "INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Glenn', 'Quagmire', 33)" ) ;

// Print the automatically generated id
echo "New record has id: " . mysqli_insert_id ( $con ) ;

mysqli_close ( $con ) ;
?>
Similar Functions
Popular Articles