Re: determine the primary key after adding a row to a table (mysql)

From: Date: Tue, 30 Apr 2002 18:41:43 +0000
Subject: Re: determine the primary key after adding a row to a table (mysql)
References: 1 2  Groups: php.db 
Request: Send a blank email to php-db+get-18915@lists.php.net to get a copy of this message
CJ, I am fairly new to PHP and MySQL but there are 2 functions that can do this. PHP has a function called mysql_insert_id to retreive the last ID and Mysql also has last_insert_id() which you can use in your query. I have used last_insert_id() with pretty good success but I would still recommend you look at the documentation for these functions. This example for last_insert_id() is off the top of my head. insert into table1 (PrimaryID,Field) would be the initial insert insert into table2 (PrimaryID,last_insert_id(),field) where last_insert_id is the value for the foreign key Hope this helps and let me know if you have any other questions. Jason "J. Wharton" <joshwhar@cc.usu.edu> wrote in message news:20020424191005.47523.qmail@pb1.pair.com... > I encountered something similar. Here is a snippet of code: > > $tdate=date("Y\\-m\\-d"); > $time=date("G\\:i\\:s"); > > $query="insert into trackinginfo (IP_Address, username, date, Time, > Processed, CommentFlag) > values ('$REMOTE_ADDR', '$username', '$tdate', > '$time', 'N', > '$commentExists')"; > > mysql_query($query) or die(mysql_error()); > > //RecordID is an auto incrementing primary key. > > $query="select RecordID from trackinginfo where IP_Address='$REMOTE_ADDR' > and username='$username' > and date='$tdate' > and Time= '$time'"; > > //used those variables as they are static for the page. And yes, that is a > bit of overkill you see there. > $result = mysql_query($query) or die(mysql_error()); > $dummyvar = mysql_fetch_object($result); > > $sid=$dummyvar->RecordID; > > > > "Cj" <calistusj@hotmail.com> wrote in message > news:20020424171846.31802.qmail@pb1.pair.com... > > is there any way to determine the primary key of a row after it's added to > a > > table in mysql? > > > > i need to do this because i have another table which requires the id from > > one table as a foreign key. > > > > > >

« previous php.db (#18915) next »