Results 1 to 2 of 2

Thread: MySQL Query for Inserting New User Into Database

  1. #1
    Join Date
    Apr 2008
    Location
    Limoges, France
    Posts
    395
    Thanks
    13
    Thanked 61 Times in 61 Posts

    Default MySQL Query for Inserting New User Into Database

    I have two tables.

    One called USERS, one called USER_INFO

    USERS has columns `user_id`, `email`, `pass_word`, `active`, `date_created`

    USER_INFO has columns `user_id`, `first_name`, `last_name`, `department`, `gender`

    My question: When a new user provides the required information, how do I write the SQL queries to ensure that the user_id for in both tables is the same, thus linking first_name, last_name, etc, TO email, pass_word, etc.

    INSERT into `users` (`email`, `pass_word`, `active`) VALUES ('$email', '$first_name', etc) will put the information into the USERS table, but now I need to put the rest of the information into the USER_INFO table while ENSURING that the `user_id` is the same for both tables.

    `user_id` in the USERS table is auto_increment and primary key.

    I know a bit about this stuff, but for some reason I can't get my head around this issue.

    Thanks a lot!

    JasonDFR

  2. #2
    Join Date
    Jul 2006
    Location
    just north of Boston, MA
    Posts
    1,806
    Thanks
    13
    Thanked 72 Times in 72 Posts

    Default

    the two tables cannot both have an auto-incrementing field that is used for the same purpose. one of those tables, will need to have a foreign key that points to the primary key in the opposite.

    To actually do the double insert, you would need to do the insert into the table with the auto-incrementing user_id field
    By checking that INSERT for no errors, you will than be able to do a second query that grabs the last inserted id, then once you have the last inserted user_id, you may do a second insert query to put the second record in the second table

    Code:
    if(query(INSERT...))
    {
       $user_id = fetch_array(query(SELECT user_id FROM ___ ORDER BY user_id DESC LIMIT 1));
       if($user_id>0)
       {
           query(INSERT....)
       }
    }

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •