views:

39

answers:

2

Consider the following tables for a LMS:

   Item (   
        ID BIGINT NOT NULL UNIQUE AUTO_INCREMENT,
        ConnectLog BIGINT NOT NULL,
        ItemClass BIGINT NOT NULL,
        ItemType BIGINT NOT NULL,
        AcqDate TIMESTAMP NOT NULL DEFAULT NOW(),
        Vendor BIGINT NOT NULL,
        Cost DECIMAL(64,2) NOT NULL DEFAULT '0.00',
        Image VARCHAR(255),
        Access INTEGER NOT NULL,
        Notes VARCHAR(255),
        PRIMARY KEY (ID)
    )

 Book   (   
        ID BIGINT NOT NULL UNIQUE AUTO_INCREMENT,
        Item BIGINT NOT NULL UNIQUE,
        ISBN BIGINT,
        Title VARCHAR(255) NOT NULL,
        Authors VARCHAR(255),
        Publisher VARCHAR(255),
        DDC VARCHAR(255),
        PubDate DATETIME,
        Edition VARCHAR(255),
        BookCase VARCHAR(255),
        Shelf VARCHAR(255),
        PRIMARY KEY (ID)
    )   

Now when a user makes an entry for Book, first an entry for Item has to be created first. But i need to find the ID for the Item entry that was created so i can use that value for Item in the Book table...

How? :/

+3  A: 

Use mysql_insert_id()

// Create Entry
$sql = "INSERT INTO TABLE () VALUES()";
mysql_query($sql);
$id = mysql_insert_id();

// Create Book
$sql = "INSERT INTO TABLE (`Item_ID`) VALUES(".$id.")";
mysql_query($sql);

I bet there is a MySQL Command you could use to do it in a single query. But, this works.

Chacha102
Right. But a doubt: On a heavy load, is it possible that another entry for Item may be executed BEFORE i reach the 'insert into Book' query?
wretrOvian
I'm not positive about this, but I imagine that the insert_id is returned to PHP after the statement finishes, and then PHP caches it somewhere. I kinda doubt that it goes and makes another query to find out. It is possible though.
Chacha102
You might want to check the documentation, I skimmed through it but didn't find much. http://us2.php.net/mysql_insert_id
Chacha102
"The value of mysql_insert_id() is affected only by statements issued within the current client connection. It is not affected by statements issued by other clients." - There we go.
Chacha102
Yeah, that seems to fit. I'll try confirming this when i can. Thanks :D
wretrOvian
A: 

According to this link, you could do an SQL query like:

INSERT INTO foo (auto,text) VALUES(NULL,'text'); # generate ID by inserting NULL
INSERT INTO foo2 (id,text) VALUES(LAST_INSERT_ID(),'text'); # use ID in second table

I haven't tested it, but it seems as though LAST_INSERT_ID() contains the last inserted ID, no matter what table it was inserted into.

If you're worried about heavy loads, and LAST_INSERT_ID() not containing the appropriate entry's ID, you could wrap these SQL statements in a transaction.

cmptrgeekken