5

i have a little difficulty in understanding how to do some INSERT SELECT.

For instance i have two tables.

TABLE : users  

 id | name   | gender  
 1  | John   | m  
 2  | Mary   | f  

TABLE : website  

 fid | url             | id  
 1   | www.desilva.biz | 2  
 2   | gidhelp.com     | 4  

Now let's say i want to add another query to the table website. I get two variables, lets say:

$user = John;
$site = "www.google.com";

i want to select the id of John from users table and insert it into website table in one statement.

How can i do it?

1 Answer 1

8

Assuming your variables are already escaped properly and are not subject to SQL injection:

INSERT
INTO    website (url, fid)
SELECT  $site, id
FROM    users
WHERE   name = $user
Sign up to request clarification or add additional context in comments.

1 Comment

I'd quote at least $user so that it matched correctly on names that contain spaces.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.