简体   繁体   English

你能在两个表之间做一个“INSERT SELECT WHERE”吗?

[英]Can you do a “INSERT SELECT WHERE” between two tables?

So I've been trying to create a simple friend system.所以我一直在尝试创建一个简单的朋友系统。 When you register, you get randomized numbers and chars of 8 in length.当您注册时,您将获得长度为 8 的随机数字和字符。 I save this number in a column to the user.我将此数字保存在一列中给用户。 I have been trying to insert the currently sessioned user(PHP), $SessionUser together with the friends' username, uidUsers using an "INSERT SELECT WHERE" statement, but something goes wrong.我一直在试图插入当前sessioned用户(PHP), $SessionUser与朋友的用户名一起, uidUsers使用‘INSERT SELECT WHERE’语句,但不顺心的事。 Heres something I have tried:这是我尝试过的东西:

$sql = mysqli_query($conn, "INSERT into friends (uid1, uid2) 
    values($sessionUser, (SELECT  uidUsers FROM users WHERE idFriendCode = $idFriendCode)");

Inside the table, friends , I have two columns, uid1 (the sessioned user/sender) and uid2 (the reciever, name of specified $idFriendCode ).表,里面friends ,我有两列, uid1 (在sessioned用户/发送器)和uid2 (在reciever,指定的名称$idFriendCode )。 I want to insert the $sessionUser to the uid1 and whatever username ( uidUsers ) that matches with the $idFriendCode to the uid2 .我想插入$sessionUser到UID1和任何用户名( uidUsers与匹配)是$idFriendCodeuid2 This does not seem to work and I don't know why.这似乎不起作用,我不知道为什么。 I imagine the problem is that I can't use a PHP variable like this.我想问题是我不能使用这样的 PHP 变量。

I know that I don't use prepared statements.我知道我不使用准备好的语句。 I have tried to implement it, but I think it's much harder than just using a basic mysqli_query().我试图实现它,但我认为它比仅使用基本的 mysqli_query() 要困难得多。

You may phrase your insert as an INSERT INTO ... SELECT :您可以将您的插入内容表述为INSERT INTO ... SELECT

INSERT into friends (uid1, uid2) 
SELECT $sessionUser, uidUsers
FROM users
WHERE idFriendCode = $idFriendCode;

Note that you should ideally be using a prepared statement here, so the above should look like:请注意,您最好在此处使用准备好的语句,因此上面的内容应如下所示:

INSERT into friends (uid1, uid2) 
SELECT ?, uidUsers
FROM users
WHERE idFriendCode = ?;

Try having a new variable for select and use it in the insert query尝试为 select 设置一个新变量并在插入查询中使用它

example:例子:

$select_qr='SELECT  uidUsers FROM users WHERE idFriendCode = $idFriendCode'

$sql = mysqli_query($conn, "INSERT into friends (uid1, uid2) 
    values($sessionUser, $select_qr)");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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