Re: mdb2 help
| From: | Lester Caine | Date: | Thu, 04 Aug 2011 08:21:54 +0000 |
| Subject: | Re: mdb2 help | ||
| References: | 1 | Groups: | php.pear.general |
| Request: | Send a blank email to pear-general+get-31188@lists.php.net to get a copy of this message | ||
Jordan Spivack wrote:
Hey everyone, sorry this is a repost from Stack Overflow but I still
desperately need a definitive answer.
I'm currently using PHP, the mdb2 package, MySQL, and the InnoDB table
engine for database development. I want to be 100% sure that when I insert
into a table and then use lastInsertID(), it will contain the correct auto
increment value for that table regardless of whether or not another user is
executing the same query. Basically, I need to lock the tables.
So for a standard series of 3 statements:
1. Insert into table A
2. $id = $mdb2->lastInsertID()
3. Insert into table B (name, fk) VALUES ('foo', $id)
what steps do I need to take to make sure $id has the value of the insert
from step 1? Is it fine the way it is? Does everything need to be in a
transaction? Do I need to add other queries to lock and release the tables?
'a definitive answer' would be to switch to a more reliable database ;)
That said, MySQL can be persuaded to serve up unique sequence/generator numbers. The normal trick when emulating how it works in other databases is to create a separate table with entries just for the 'id's that you are using. Then simply get the next id from that table and increment that id in the one operation. So you can safely use the id to put entries into table A and table B without the 'autoincrement' being necessary. 'RETURNING' is another extension to SQL that was added in part to get around this problem, but SEQUENCE is the most reliable way and used in other databases.
--
Lester Caine - G8HFL
-----------------------------
Contact - http://lsces.co.uk/wiki/?page=contact
L.S.Caine Electronic Services - http://lsces.co.uk
EnquirySolve - http://enquirysolve.com/
Model Engineers Digital Workshop - http://medw.co.uk//
Firebird - http://www.firebirdsql.org/index.php