SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Enthusiast
    Join Date
    Dec 2000
    Posts
    85
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I have 2 tables which I need to insert information with the same submit event. First table has an auto increment integer id field as the primary key. I don't have any problems with inserting information into it. But I have a big problem when I want to insert information to the second one. I need to know the id of the row inserted into the first table so that I can insert it as a seperate field into the second table. I need to store which rows of second table are related to which rows in the first table.

    thank you

  2. #2
    SitePoint Addict zoordaan's Avatar
    Join Date
    Feb 2001
    Location
    NYC/Texas
    Posts
    348
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Use the mysql_insert_id function:

    $entry_id=mysql_insert_id(); <- assign the last insert id to a variable then use that variable when inserting to the second table.

    You can read more about the function in the manual: http://www.php.net/manual/en/functio...-insert-id.php

  3. #3
    SitePoint Zealot moshe_be's Avatar
    Join Date
    Dec 2000
    Posts
    169
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The last_inserted_id never worked for me, so I just use this query:

    'SELECT LAST_INSERT_ID() last_id'

  4. #4
    SitePoint Guru
    Join Date
    Jan 2001
    Location
    Alkmaar, Netherlands
    Posts
    710
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    typo I think --->
    'SELECT LAST_INSERT_ID() as last_id'?

  5. #5
    SitePoint Zealot moshe_be's Avatar
    Join Date
    Dec 2000
    Posts
    169
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Putting AS is optional, you can make alias without it.

  6. #6
    Dumb PHP codin' cat
    Join Date
    Aug 2000
    Location
    San Diego, CA
    Posts
    5,460
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    However your query will return a row for each record found not just one with the last id in it. Yo ucan get around thi s by using

    SELECT DISTINCT LAST_INSERT_ID() as last_id from tablename
    Please don't PM me with questions.
    Use the forums, that is what they are here for.


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
  •