Search code examples
phpmysqlmysql-insert-id

mysql_insert_id() to view value of last inserted records


I have a PHP script that inserts data into a mysql database. The table has an auto increment column.

I want to use the mysql_insert_id() function to get teh value of the last inserted record.

For some reason this is returning the value 0 where the autoid column has a value of 300037.

Any assistance is appreciated. Thank you.

my code snippet is below:

$sqlinsertdelivery="INSERT INTO deliverydetails (`LoadID1`,`deliveryroute`,`source`,`destination`,`route`,`CollectionArea1`, `CollectionArea2`, `CollectionArea3`, `CollectionArea4`, `CollectionDate`, `collectiontime`, `Destination1`, `Destination2`, `Destination3`, `Destination4`, `ArrivalDate`, `ArrivalTime`, `DeliveryCreationDateTime`, `DeliveryCreatedBy`,`comments`,`trailertype`) 
 VALUES
 ($loadnumber,'$route1','Hulamin','$dest1','$_SESSION[sessionrouteid]','$_POST[dispatchid1]','$_POST[dispatchid2]','$_POST[dispatchid3]','$_POST[dispatchid4]','$_POST[coldatetime]','$_POST[deltime]','$_POST[drop1]','$_POST[drop2]','$_POST[drop3]','$_POST[drop4]','$_POST[arrivedatetime]','$_POST[arrivetime]',CURRENT_TIMESTAMP,'$session->username','$_POST[comments]','$_POST[vehicletype]')
 ";
  if (!mysql_query($sqlinsertdelivery,$con))
   {
   die('Error with insert statement: ' . mysql_error());
   }


$delid = mysql_insert_id();
echo $delid;

Solution

  • Long shot, but first try replacing mysql_insert_id(); with mysql_insert_id($con);

    On a side note, PLEASE tell me this is code that will not be in production.