- SPLessons

Get Last inserted record ID in PHP

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Get Last inserted record ID in PHP

 Get Last inserted record ID in PHP


 

Description :

I have two tables one is ‘Persons’ and other is ‘orders’. If you want insert Persons table primmary_key(unique id) into oredrs table the below pieceof code will help you. The below ‘$last_record_id’ is primary_key of ‘Persons’ table that inserted into ‘Orders’ table.

 

Add below code will show you to Get Last inserted record ID in PHP


 $query1="insert into persons(column1, column2, column3, column4) values('value1', 'value2', 'value3', 'value4')";
		$res1 = $db->query($query1);
		$last_record_id=$db->lastInsertId(); // ID of last inserted record in your table

 $query2="insert into table2(column1, column2, column3, column4) values('value1', '$last_record_id', 'value3', 'value4')";
		$res2 = $db->query($query2);