skij
asked on
MySQL / PHP: Get value of AUTO_INCREMENT for new record
Here is the structure of the MySQL database I am using:
Using PHP, how can I determine the value of `xyz_id` for the record that was inserted, without risking a race-condition problem?
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;
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: ???';
ASKER
I am using MySQLI (insert_id).
Are you sure this will not risk a race condition?
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;
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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