Link to home
Start Free TrialLog in
Avatar of skij
skijFlag for Canada

asked on

MySQL / PHP: Get value of AUTO_INCREMENT for new record

Here is the structure of the MySQL database I am using:
CREATE TABLE `xyz` (
  `xyz_id` int(11) NOT NULL AUTO_INCREMENT,
  `x` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `y` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `z` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`xyz_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Open in new window


Using PHP, how can I determine the value of `xyz_id` for the record that was inserted, without risking a race-condition problem?
  $sql = "INSERT INTO `xyz` (
     `x`, 
     `y`,
     `z`
   ) VALUES (
     'x',
     'y',
     'z'
   )";
  $result = $crm_db->query($sql);
  echo 'The `xyz_id` of the most recently added record is: ???';

Open in new window

Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

What lib are you using

mysql - (mysql_insert_id) NB this library has been deprecated and you should update it to mysqli / pdo
http://php.net/manual/en/function.mysql-insert-id.php

PDO::lastInsertId
http://php.net/manual/en/pdo.lastinsertid.php

MySQLI (insert_id)
http://php.net/manual/en/mysqli.insert-id.php

There won't be a race condition because the last insert id is set by session
http://php.net/manual/en/mysqli.insert-id.php
Avatar of skij

ASKER

I am using MySQLI (insert_id).  

Are you sure this will not risk a race condition?
echo 'The `xyz_id` of the most recently added record is: ' .  $crm_db->insert_id;
  

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial