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.

The INSERT … SELECT … syntax is like this:


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’.