Re: Getting last record ID created from DB

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Philip Thompson wrote:

> On Mar 16, 2007, at 10:28 PM, Jeff wrote:
> 
>> Is there a way to get the last Record # created by the DB.
>>
>> Example:
>>
>> User_ID = auto_increment
>> f_name = varchar
>> l_name = varchar
>> e-mail = varchar
>> b_date = varchar
>> pic = varchar
>>
>>
>> Since user_id is an auto_inc field I submit it as a NULL, also I
>> haven't
>> started the code for a picture yet either so I have it set to NULL
>> at this
>> moment.
>> My code is:
>>
>> $query = "INSERT INTO `t_users` (`user_id`, `f_name`, `l_name`,
>> `e_mail`,
>> `b_date`, `pic`) VALUES ('', '$f_name', '$l_name', '$e_mail',
>> '$b_date',
>> '')";
>> $result = mysql_query($query);
>> if(!$result)
>> {
>> die("Could not query the database: <br/>".mysql_error());
>> }
>> echo "Your Player information has been stored OK.<br />";
>>
>> what code could I add here to make the following line work?
>>
>> echo "REMEMBER your USER ID# you will need it when creating
>> Characters!! It
>> is: $user_id"; <----- I want to show the "user_id" just created here.
>>
>> Thanks in advance!
> 
> 
> For auto increment values, you don't have to specify the id. For
> example:
> 
> INSERT INTO t_users (f_name, l_name, e_mail, b_date, pic)
> VALUES ('$f_name', '$l_name', '$e_mail', '$b_date', null);
> 
> Then to find the latest entry:
> 
> SELECT user_id FROM t_users ORDER BY user_id DESC limit 1;
> 
> Hope that helps.

This too is almost certainly going to return the wrong user_id if the site
has any sort of concurrency. If in the time between the user creating an ID
and your code retrieving the ID, another user with another PHP process
could easily have executed the same insert.

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux