在正确的SQL上挣扎。尝试将数据插入表中,但只需插入另一个表中的一列
INSERT INTO customer_details (user_id, firstName, lastName, email, mobile)
VALUES (SELECT id FROM users WHERE username = ?, ?, ?, ?, ?');
使用以下“bind_param”函数,我将为变量分配变量
$stmt->bind_param('ssssi', $username, $first_name, $last_name, $email, $mobile_num);
非常感谢!
答案 0 :(得分:1)
您需要insert . . . select
形式的insert
:
INSERT INTO customer_details (user_id, firstName, lastName, email, mobile)
SELECT id, ?, ?, ?, ?
FROM users
WHERE username = ?;
请注意,这会更改参数的顺序,因为where
中的比较现在是最后一次。
答案 1 :(得分:1)
尝试13.2.5.1 INSERT ... SELECT Syntax:
INSERT INTO
customer_details (user_id, firstName, lastName, email, mobile)
SELECT id, ?, ?, ?, ?
FROM users
WHERE username = ?
编辑:检查以下示例以了解insert ..select的工作原理:
创建两个表:one
和two
mysql> CREATE TABLE one (x int, y int);
Query OK, 0 rows affected (0.58 sec)
mysql> CREATE TABLE two (x int, y int);
Query OK, 0 rows affected (0.22 sec)
在表two
中插入了一些行:
mysql> INSERT INTO two (x, y) VALUES (1, 2), (2, 4), (3, 5), (6, 7);
Query OK, 4 rows affected (0.19 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM `two`;
+------+------+
| x | y |
+------+------+
| 1 | 2 |
| 2 | 4 |
| 3 | 5 |
| 6 | 7 |
+------+------+
4 rows in set (0.03 sec)
表one
为空:
mysql> SELECT * FROM `one`;
Empty set (0.02 sec)
现在,在表one
中插入表x
中表one
== y
中的每个two
,表中的y
one
等于变量的值(例如,脚本中来自用户的一些数据)。此外,如果条件为真,则tow
的行将执行插入操作。
mysql> SET @a = 100; -- variable
Query OK, 0 rows affected (0.00 sec)
mysql> INSERT INTO one (x, y) SELECT y, @a FROM two WHERE y IN (2, 4, 7) ;
Query OK, 3 rows affected (0.12 sec)
Records: 3 Duplicates: 0 Warnings: 0
现在表one
是:
mysql> SELECT * FROM one;
+------+------+
| x | y |
+------+------+
| 2 | 100 | -- 100 is like value from use not from table `two`
| 4 | 100 |
| 7 | 100 |
+------+------+
3 rows in set (0.00 sec)
答案 2 :(得分:0)
尚未对此进行测试,但请尝试:
INSERT INTO customer_details (user_id, firstName, lastName, email, mobile)
(SELECT id,?, ?, ?, ? FROM users WHERE username = ?)
答案 3 :(得分:0)
也许:
INSERT INTO `customer_details` (`user_id`, `firstName`, `lastName`, `email`, `mobile`)
SELECT `id`, ?, ?, ?, ? FROM `users` WHERE `username` = ?
$stmt->bind_param('ssssi', $first_name, $last_name, $email, $mobile_num, $username);