I\'am new to MySQL, so please be nice :)
I would like to insert data from a php form into 3 different tables, which all have foreign keys. How can I write an insert
You can do it in 3 Methods:
First & Recommended. USING SELECT IN THE INSERT VALUE:
INSERT INTO user (name) VALUES ('John Smith'); INSERT INTO user_details (id, weight, height) VALUES ((SELECT id FROM user WHERE name='John Smith'), 83, 185);
Second. USING LAST_INSERT_ID IN THE INSERT VALUE:
INSERT INTO a (id)
VALUES ('anything');
INSERT INTO user_details (id, weight, height)
VALUES (LAST_INSERT_ID(),83, 185);
Third. USING PHP SCRIPT
<?php
// Connecting to database
$link = mysql_connect($wgScriptsDBServerIP, $wgScriptsDBServerUsername, $wgScriptsDBServerPassword, true);
if(!$link || !@mysql_SELECT_db($wgScriptsDBName, $link)) {
echo("Cant connect to server");
exit;
}
// Values to insert
$name = 'John Smith';
$weight = 83;
$height = 185;
// insertion to user table
$sql = "INSERT INTO user (name) VALUES ('$name')";
$result = mysql_query( $sql,$conn );
// retrieve last id
$user_id = mysql_insert_id( $conn );
mysql_free_result( $result );
// insertion to user_details table
$sql = "INSERT INTO user_details (id, weight, height) VALUES ($user_id, $weight, $height)";
$result = mysql_query( $sql,$conn );
mysql_free_result( $result );
?>
1) The sense of foreign_key is to associate a value in a field with a pre_existing value somewhere else. So you should make your inserts in a logic order.
2) If you want to avoid logical restrictions you should
SET foreign_key_checks = 0 // disable key checks in server
INSERT ... // any order
INSERT ...
...
SET foreign_key_checks = 1
You're most likely going to have to insert things in order of their dependence. So if you have three tables (A, B, and C) we'll assume C depends on B and B depends on A. We'll also assume each table has primary keys AID, BID, and CID respectively.
There is an error in your syntax for the method 1.
INSERT INTO user_details (id, weight, height)
VALUES (SELECT(id FROM user WHERE name='John Smith'), 83, 185);
should be
INSERT INTO user_details (id, weight, height)
VALUES ((SELECT id FROM user WHERE name='John Smith'), 83, 185);