MySQL - How to insert into multiple tables with foreign keys

前端 未结 4 1707
鱼传尺愫
鱼传尺愫 2020-12-14 10:58

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

相关标签:
4条回答
  • 2020-12-14 11:29

    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 );
    ?>
    
    0 讨论(0)
  • 2020-12-14 11:35

    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
    
    0 讨论(0)
  • 2020-12-14 11:36

    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.

    1. You'd insert your row into A and get AID.
    2. Then you'd insert your row into B using the AID you got from step 1.
    3. Then you'd insert your row into C using the BID (and perhaps AID) you got from step 2 (and perhaps 1)
    0 讨论(0)
  • 2020-12-14 11:42

    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);
    
    0 讨论(0)
提交回复
热议问题