How to get last insert id safely?
am 06.12.2007 03:04:12 von jacky
Hi All,
How to get last insert id safely in php with persistent connection to
mysql?because there may be larger concurrence requests to the php to query
insert statements.Example,the php query following two sql statements:
mysql_query("insert into tb(id,name) values(null,$username)");
$res = mysql_query("select last_insert_id()");
And in any time,user A insert one row to the table tb,and the same time
before user A query last_insert_id(),user B insert another row to the same
table too.
In this situation,will user A or B query last_insert_id() function get the
correct id for he/her just insert?
Any ideas?Thanks!
Regards
Jacky
--
PHP Database Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php
Re: How to get last insert id safely?
am 06.12.2007 03:45:57 von Mazzu
If the first query doesn't fail you can be sure that last_insert_id()
for A while return the ID of his name because
1) "The ID that was generated is maintained in the server on a
per-connection basis. This means that the value returned by the function
to a given client is the first AUTO_INCREMENT value generated for most
recent statement affecting an AUTO_INCREMENT column by that client."
(
http://dev.mysql.com/doc/refman/5.0/en/information-functions .html#function_last-insert-id
)
2) When a script use mysql_pconnect() it take a connection and then php
marked this connection as reserved until the script ends.
(http://www.php.net/manual/en/features.persistent-connection s.php)
Note : For Apache 1, it's ok according to the doc ("They cause the child
process to simply connect only once for its entire lifespan, instead of
every time it processes a page that requires connecting to the SQL server.
This means that for every child that opened a persistent connection will
have its own open persistent connection to the server.") and I can't
find if it should work also for Apache 2.0 and 2.2
For your information :
http://www.mysqlperformanceblog.com/2006/11/12/are-php-persi stent-connections-evil/
"Jacky" wrote:
> Hi All,
> How to get last insert id safely in php with persistent connection to
> mysql?because there may be larger concurrence requests to the php to query
> insert statements.Example,the php query following two sql statements:
>
> mysql_query("insert into tb(id,name) values(null,$username)");
> $res = mysql_query("select last_insert_id()");
>
> And in any time,user A insert one row to the table tb,and the same time
> before user A query last_insert_id(),user B insert another row to the same
> table too.
> In this situation,will user A or B query last_insert_id() function get the
> correct id for he/her just insert?
>
> Any ideas?Thanks!
>
> Regards
> Jacky
--
PHP Database Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php