SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Aug 2011
    Posts
    20
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    How to insert and select the data from the same table?

    Hi,

    I want to insert and select the data from the same table.I am using following query to insert and select the data from the same table. However, I am not able to insert the data.

    Is there any method to do this?

    $sql=mysql_query("INSERT INTO users (name,ref_no) VALUES( '$name', (SELECT id FROM users WHERE name='$name') )");


    id is AUTO_INCREMENT


    Would greatly appreciate your help.

    Thank you.

  2. #2
    From Italy with love silver trophybronze trophy
    guido2004's Avatar
    Join Date
    Sep 2004
    Posts
    9,412
    Mentioned
    149 Post(s)
    Tagged
    4 Thread(s)
    The INSERT ... SELECT ... syntax is like this:
    Code:
    INSERT INTO users (name,ref_no) 
    SELECT 
        '$name'
      , id 
    FROM users 
    WHERE name='$name'
    But in this case it'll only work if there's already at least one row with name='$name' in the users table, and a new row will be added for each id already present in the users table where name='$name'.


Tags for this Thread

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
  •