note 23719 added to function.mysql-insert-id
| From: | david at NOSPAM_enderson dot net | Date: | Thu, 25 Jul 2002 18:27:09 +0000 |
| Subject: | note 23719 added to function.mysql-insert-id | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-33562@lists.php.net to get a copy of this message | ||
If you are worried about what happens when multiple pages are executing your code simultaneously,
worry no longer.
This function is 100% threadsafe.
On line 1720 in the PHP source file: php-4.1.2/ext/mysql/libmysql/libmysql.c it shows that the
function does not get its value from the database at the time you call it (which was our concern).
Whenever a MySQL query is executed, MySQL returns a whole bunch of raw bytes to PHP, which it parses
up into useful info. One of those items is the generated id which PHP immediately stores in a
variable. When you call mysql_insert_id(), the value of that variable is returned. Thus there is
no chance for another query hitting simultaneously to mess it up because there is no second call to
the database anywhere.
I believe this is true for versions after PHP 4.1.2 also.
Use this example code and you will never go wrong:
(Obviously, you need to change $db, $username, and $password to the values appropriate for your
system.)
$db = "mydatabase";
$username = "username";
$password = "password";
$li = mysql_connect("", $username, $password);
mysql_select_db($db, $li);
$query = "[put your query here]";
$result = mysql_query($query, $li);
$recent_id = mysql_insert_id($li);
[process your result here]
IMPORTANT NOTE: You should ALWAYS pass mysql_query() and mysql_insert_id() the database link
identifier variable returned by the mysql_connect() function to BE SURE that you have the right ID
being returned. (It shouldn't matter if you only have one database connection open at a time,
but getting in the habit of providing the link identifier will save you a big headache someday.)
--
http://www.php.net/manual/en/function.mysql-insert-id.php
http://master.php.net/manage/user-notes.php?action=edit+23719
http://master.php.net/manage/user-notes.php?action=delete+23719
http://master.php.net/manage/user-notes.php?action=reject+23719