panthro
panthro

Reputation: 24099

Insert with a Select query

I've seen this question asked before, but with the select getting all of the vars for the insert, how can I perform an insert with part strings, part select query?

For example:

INSERT INTO users (first_name, surname, foreign_id) 
VALUES ('John', 'Smith', SELECT id FROM foreign_ids WHERE name = 'John')

Upvotes: 2

Views: 39

Answers (2)

Mark Salvania
Mark Salvania

Reputation: 484

Create variable for your select query

$sql = "SELECT id FROM foreign_ids WHERE name = 'John'"; $foreign_id = $conn->query($sql);

Then put $foreign_id inside your insert query

INSERT INTO users (first_name, surname, foreign_id) VALUES ('John', 'Smith', '{$foreign_id}')

Upvotes: 0

ScaisEdge
ScaisEdge

Reputation: 133400

use insert select this way

INSERT INTO users (first_name, surname, foreign_id)  
SELECT 'John', 'Smith',  id FROM foreign_ids 
WHERE name = 'John';

move the literal string you have in value as literal string in corresponding columns in select

Upvotes: 3

Related Questions