Re: Getting last record ID created from DB

From: Date: Sat, 17 Mar 2007 13:45:02 +0000
Subject: Re: Getting last record ID created from DB
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-250750@lists.php.net to get a copy of this message
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 (Žø_ > b(ÕÛVÓ Igé–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! There are a couple ways to do this, it is presumed that there is some unique field beyond just user id, for instance e_mail. Just select the id based on email address. It is typically bad form to rely on specifics of a particular SQL engine for architecture. The other way is, if you were using a real database, use a sequence. Select next value from the sequence, and insert the row into t_users with id already populated. Last you could make user_id some sort of known unique number, like a GUID or something where you can generte it in the web code and save yourself the database hit.

« previous php.general (#250750) next »