Re: Insert ID

From: Date: Fri, 16 Aug 2002 13:47:09 +0000
Subject: Re: Insert ID
References: 1 2  Groups: php.pear.general 
Request: Send a blank email to pear-general+get-2133@lists.php.net to get a copy of this message
On Thu, 15 Aug 2002 21:57:02 +0200 Patrik Wallstrom <pawal@blipp.com> wrote: > On Thu, 15 Aug 2002, Markus Wolff wrote: > > > > You people may have heard this one many times but here goes. > > > > > > Whats the easiest and most database independent way of getting an id back > > > from an insert you have just performed using Pear. > > > > "The easiest and most database independent way" would be _not_ to get an > > id _back_, but to get the next id for your insert _before_ it is > > performed. To achieve this, use sequences instead of auto_increment > > fields. PEAR::DB emulates sequences for databases that don´t support > > them natively (like MySQL). > > That would be no good if for example you insert something in a web > application, and the next step would be to display that record with a > redirect. The semi-bad way to solve this without getting the inserted > id would be to use an already known unique id, but that wouldn't be > good code. ...but you do understand the concept of sequences, do you? In a scenario like the one you mentioned, you can do it both ways: Without sequences ================= 1. Execute INSERT query (without any ID, cause it´s auto_increment) 2. Get the ID using $lastID = mysql_insert_id() 3. Redirect to "display.php?id=$lastID" With sequences ============== 1. Get a new ID from a sequence: $lastID = $db->nextId("nameOfSequence") 2. Execute INSERT query using $lastID 3. Redirect to "display.php?id=$lastID" There ain´t much difference, is there? Except for one thing: The method without sequences is not compatible across databases, the method using sequences is. Regards, Markus -- Markus Wolff <wolff@21st.de>

« previous php.pear.general (#2133) next »