0

たとえば、2 つのテーブルを持つデータベースがあります。最初のテーブル (table1) には次のものがあります。

  userId int not null auto_increment primary key
  userEmail
  userPassword

userId は、自動インクリメントされる主キーです。次のテーブル (table2) には次のものがあります。

 userProfileId int not null auto_increment primary key
 userAge
 userGender
 userId 

userId (table2 から) は、table1(userId) を参照する外部キーです。両方のテーブルのすべての情報を INSERT INTO し、table2 の userId が table1 から参照する主キーを自動的に取得する方法はありますか? または、テーブルごとに複数の INSERTS を実行し、外部キーを明示的に同じ値にする必要がありますか。

4

1 に答える 1

0

以下のようにmysqlの「Last_insert_id」を使用できます-

<?php
$user_query="INSERT INTO accounts (userId,userEmail,userPassword) VALUES (NULL,'saving@gmail.com','XXXXXXXXX')";
$profile_query="INSERT INTO transactions(userProfileId,userAge,userGender,userId) VALUES (NULL,25,'m'LAST_INSERT_ID)";

$a_query=mysql_query($user_query);
$t_query=mysql_query($profile_query);
?>

注: mysql_* は非推奨です。代わりに、PDO ステートメントを使用できます。

参照: http://in3.php.net/manual/en/function.mysql-insert-id.php

参照: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id

于 2013-10-24T02:39:34.150 に答える