note 59718 added to function.mysql-insert-id
| From: | heiligkind at yahoo dot de | Date: | Wed, 14 Dec 2005 09:31:55 +0000 |
| Subject: | note 59718 added to function.mysql-insert-id | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-100116@lists.php.net to get a copy of this message | ||
If you insert a data row by using the ON DUPLICATE KEY UPDATE clause in an INSERT-statement, the
mysql_insert_id() function will return not the same results as if you directly use LAST_INSERT_ID()
in MySQL.
See the following example:
<?
// insert a datarow, primary key is auto_increment
// value is a unique key
$query = "INSERT INTO test (value) VALUES ('test')";
mysql_query( $query );
echo 'LAST_INSERT_ID: ',
mysql_query( "SELECT LAST_INSERT_ID()" ),
'<br>mysql_insert_id: ',
mysql_insert_id();
?>
This will print:
LAST_INSERT_ID: 1
mysql_insert_id: 1
In this case the function returns the same as the MySQL-Statement.
But see the insert on an existing key:
<?
$query = "INSERT INTO test (value)
VALUES ('test')
ON DUPLICATE KEY UPDATE value = 'test2'";
mysql_query( $query );
echo 'LAST_INSERT_ID: ',
mysql_query( "SELECT LAST_INSERT_ID()" ),
'<br>mysql_insert_id: ',
mysql_insert_id();
?>
This will print:
LAST_INSERT_ID: 2
mysql_insert_id: 1
By using the ON DUPLICATE KEY UPDATE clause, only the old datarow will be modified, if the INSERT
statement causes a duplicate entry, but the LAST_INSERT_ID() function returns the next
auto_increment value for the primary key, which is by the way not set as the next auto_increment
value in the database.
The mysql_insert_id() function returns the primary key of the old (and changed) data row. For me
this is the right operation method, because the LAST_INSERT_ID() function returns a value which is
not referenced to a data row at all.
Greets from Munich.
heiligkind
----
Manual Page -- http://www.php.net/manual/en/function.mysql-insert-id.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+59718
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+59718&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+59718&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+59718&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+59718&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+59718&report=yes&reason=non-english
Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+59718&report=yes&reason=already+in+docs
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+59718&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+59718&report=yes
Search -- http://master.php.net/manage/user-notes.php