Current Location: Home> Function Categories> mysql_insert_id

mysql_insert_id

Get the ID generated by the previous INSERT operation.
Name:mysql_insert_id
Category:Uncategorized
Programming Language:php
One-line Description:Get the auto-increment ID value of the last inserted record

Function name: mysql_insert_id()

Function Description: This function is used to obtain the autoincrement ID value of the last inserted record.

Applicable version: This function was introduced in PHP 4, but was deprecated in PHP 5.5.0 and removed in PHP 7.0.0. It is recommended to use mysqli or PDO extension instead.

Syntax: mysql_insert_id($link)

parameter:

  • $link: Optional parameter, indicating the connection to the MySQL server. If this parameter is omitted, the connection returned by the most recent mysql_connect() or mysql_pconnect() function is used.

Return value: Returns an integer representing the self-increment ID value of the last inserted record.

Example:

  1. Use the default connection to get the ID of the last inserted record:
 $link = mysql_connect("localhost", "username", "password"); mysql_select_db("database", $link); $query = "INSERT INTO users (name) VALUES ('John')"; mysql_query($query, $link); $lastInsertedId = mysql_insert_id(); echo "Last inserted ID: " . $lastInsertedId;
  1. Use the specified connection to get the ID of the last inserted record:
 $link = mysql_connect("localhost", "username", "password"); mysql_select_db("database", $link); $query = "INSERT INTO users (name) VALUES ('John')"; mysql_query($query, $link); $lastInsertedId = mysql_insert_id($link); echo "Last inserted ID: " . $lastInsertedId;

Notes:

  • Since this function has been deprecated and removed, it is recommended to use the corresponding functions in mysqli or PDO extensions instead.
  • If no INSERT query was executed before inserting the record, or the last query was not an INSERT statement, the mysql_insert_id() function will return 0.
  • If the last inserted table does not have an autoincrement ID column, the mysql_insert_id() function will return 0.
Similar Functions
Popular Articles