0

I have a DB with table1 (id, name_id, value) and table2 (id, name, other)

then I have some data

$name = 'a name';
$value = 'a value';

I want to use the value $name as table2.name to get table2.id and insert it into table1 as table1.name_id but then I also want to insert $value into table1.

when doing a SELECT I could use JOIN, but the only thing I've found for INSERT is to use a SELECT query instead of VALUES

However, I want to use a value from table2 (id) as well as insert $value but the SELECT method seems to only copy data from one table (table2) to another

Edit: pseudo SQL

<pre>INSERT INTO `table1` (`name_id`, `value`)
VALUES ((`table2`.`id` WHERE `table2`.`name` = $name), $value)</pre>
2
  • Please give an example in pseudo SQL because I cannot follow what you are trying to say here at all Commented Aug 26, 2015 at 20:22
  • updated it, but I think juergen (and Kevin's, although I don't use PDO) are what I'm looking for. Commented Aug 26, 2015 at 20:27

2 Answers 2

2

Something like this should work (assuming PDO since you didn't specify):

$preparedStmt = $pdo->prepare("INSERT INTO table1 (name_id,value)
    SELECT id, :value FROM table2 WHERE name=:name");
$preparedStmt->execute(array('name'=>$name,'value'=>$value));
Sign up to request clarification or add additional context in comments.

Comments

1
insert into table1 (name_id, other)
select id, 'just some static data or data from a variable'
from table2
where name = '$name'

I inserted the variable for better readability. But I recommend using Prepared Statements instead.

2 Comments

sorry, I just updated the question. the method you posted is the one I've found, but how could I add another bit of data (which isn't in table2 into a table1 column?
ah. I am using prepared statements as well, so would it be select id, ? and then I would just bind params as usual?

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.