Inserting data into two tables with one Form

Discussion in 'PHP' started by sirab33, Nov 3, 2009.

  1. #1
    I've been researching this for days on end and nothing I've tried works.

    I have a database called "members" which has two tables: "membersInfo" and "membersExtraInfo".

    the gist of my code is as follows:

    $connection = mysql_connect("localhost","root","root");
    if (!$connection)
       { die('Could not connect: ' . mysql_error());  }
    		  
    mysql_select_db("members", $connection);
    $sql="INSERT INTO membersInfo (email, socialsecurity, taxid) VALUES ($email, $socialsecurity, $taxid)";
    $sqlTwo="INSERT INTO membersExtraInfo (name, lastname, username, password) VALUES ($name, $lastname, $username, $password)";
    
    Code (markup):

    I see a lot of posts where "mysql_insert_id()" is being used but I don't understand why or how its used or even needed.
    I've also tried this with "mysql_query( $sql,$connection )" and without - doesn't seem to make a difference.

    I just want the user to enter info into a form, hit "submit" and have the data be dispersed into the two different tables. (And please don't ask why it can't just be all put into the same table! Its a long story :))


    thanks !
     
    sirab33, Nov 3, 2009 IP
  2. DSaNDun

    DSaNDun Peon

    Messages:
    13
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    First of all you have to have a ID or some Unique identifier on both tables.

    I use "id" as that unique field. It is a auto_increment field. once you add a record to your 1st table it will automatically assigns next value (such as 1 , 2 , 3 ...... 10).
    You don't need to add that field to your 1st sql query.

    so it will go like this
    $sql=@mysql_query("INSERT INTO membersInfo (email, socialsecurity, taxid) VALUES ($email, $socialsecurity, $taxid)");
    
    PHP:
    Then I use @mysql_insert_id() to get that auto incremented value

    $member_id=intval(@mysql_insert_id());
    PHP:
    now you can link both tables by using that id field

    $sqlTwo=@mysql_query("INSERT INTO membersExtraInfo (id, name, lastname, username, password) VALUES ($member_id, $name, $lastname, $username, $password)");
    PHP:
    :)
     
    DSaNDun, Nov 3, 2009 IP
  3. xenon2010

    xenon2010 Peon

    Messages:
    237
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #3
    you need to add new column called id with auto-increment in first table..
    the second table should also has 2 new columns the first one ID which is incremental and second one is first_table_id...
    the first_table_id should contain the ids of the first table..
    this method will connect both tables..
     
    xenon2010, Nov 4, 2009 IP