[英]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)
我有一个具有
table1 (id, name_id, value)
和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
. 我想使用值
$name
作为table2.name
来获取table2.id
并将其作为table1.name_id
插入到table1
,但是我也想将$value
插入到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
在执行
SELECT
我可以使用JOIN
,但是我发现INSERT
的唯一一件事就是使用SELECT
查询而不是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 但是,我想使用
table2
( id
)中的一个值以及插入$value
但是SELECT
方法似乎只将数据从一个表( table2
)复制到另一个table2
Edit: pseudo SQL 编辑:伪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): 这样的事情应该可以工作(假设您未指定PDO):
$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.
但是我建议改为使用预备语句 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.