简体   繁体   中英

PHP MySQL foreign-key auto insert

So basically what I am trying to do is when a user of my site creates a new account on our register page, I'd like the primary key from the newly created row on the User table (basic info table, email, password, etc.) to be inserted into a new row on the Profile table (more descriptive info, about me, display name, etc.)

I'd like to do this in PHP and any help would be appreciated.

if you are using mysqli look at: http://www.php.net/manual/en/mysqli.insert-id.php

Get the id after your first insert and then use this in your next insert.

If doing it "in php" isn't really a requirement, then you can use MySQL's built in Trigger mechanism to do this update.

Triggers cause something to happen AFTER or BEFORE an event(INSERT, UPDATE,DELETE)

So your trigger would be:

CREATE TRIGGER thistrigger AFTER INSERT
ON User FOR EACH ROW
UPDATE PROFILE SET "whatever"

On Triggers: http://dev.mysql.com/doc/refman/5.0/en/create-trigger.html

I think there isn't a really elegant way in MySQL, basically because INSERT doesn't return anything. PostgreSQL does allow for an INSERT... RETURNING clause, but that's an extension.

That said, if you're using the mysql_* functions in PHP, you can use mysql_insert_id , which might suffice for your needs (ie if your primary key is an AUTO INCREMENT integer).

If you are using a mysql database, you could alternatively do another query call from php with the following query:

"SELECT LAST_INSERT_ID();"

More info about it here: http://www.jpgtutorials.com/mysql-last_insert_id-function

It is connection specific. Concurrent inserts from different connections won't affect the current connection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM