简体   繁体   中英

How can I mix PHP variables with SELECT data in a MySQL INSERT query?

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>

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));
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM