Receiving the last id of an insert with PHP and MySQL

Code to get the last insert ID of a tuple.

We created this article to answer a question that we have ever been asked in our email. It is about getting the last identifier of a record inserted in the database, programming with PHP and with the MySQL database.

It really is a very easy question to solve, thanks to PHP’s rich set of functions for working with MySQL databases. There is a function that directly returns the identifier of the last insertion, using the connection to the database that is passed to it as a parameter, or the last connection used in the event that no parameter is indicated.

mysql_insert_id($connectid)

Example of use

Let’s see an example of the use of this function, in which the necessary actions are performed to insert an element in the database. In this example we will use a database called “test” and the table “client”.

//connect to the database $connectid = mysql_connect(“localhost”,”root”,””); //select the database to use mysql_select_db(“test”,$connectid); //Element insertion statement $ssql = “INSERT INTO client (client_name, cif, address, email) VALUES (‘xxx Company name’, ‘B3331113’, ‘C/ Corona 2’, ‘eepe@relll.com’) “; //insert it into the database if (mysql_query($ssql,$connectid)){ //get the last id $last_id = mysql_insert_id($connectid); echo $last_id; }else{ echo “Insert failed”; }

First, it connects to MySQL and selects the database to use. An insert SQL statement is then generated into an assumed customer table. If the execution of this statement is correct, the last ID is received with the insert_id() function. If the execution of the statement fails, it displays an error message.

Notice that insert_id() receives the connection identifier, returned by mysql_connect(), and not the query result identifier, which is returned by mysql_query() when select statements are executed against the database.

Loading Facebook Comments ...
Loading Disqus Comments ...