我有一个像这样的 MySQL 查询:
SELECT cp.plan_name, cp.plan_time FROM courses c
INNER JOIN course_to_plan cpl ON cpl.course_id = c.course_id
INNER JOIN courseplans cp ON cp.plan_id = cpl.plan_id
WHERE cpl.course_id = '$course_id';
这将输出数据,例如:
+----------------------------+-----------+
| plan_name | plan_time |
+----------------------------+-----------+
| Plan number one name | 6 |
| Plan number two name | 6 |
| Plan number three name | 10 |
+----------------------------+-----------+
我希望在提交表单时将这些行插入到新表中。
我如何继续编写我的 update.php
以使其将值插入到表 newtable
中?
if (isset($_POST['submit'])) {
$course_id = $_POST['course_id'];
$course_result = mysql_query
("SELECT cp.plan_name, cp.plan_time FROM courses c
INNER JOIN course_to_plan cpl ON cpl.course_id = c.course_id
INNER JOIN courseplans cp ON cp.plan_id = cpl.plan_id
WHERE cpl.course_id = '$course_id'");
/* I want the result of the above rows to be inserted in the table
newtable which has the columns plan_name, plan_time */
我不想承认我在 PHP 和 MySQL 方面完全没用,但我正在努力学习。我想我必须创建某种数组来存储结果,然后遍历插入,但我不知道如何做。
最佳答案
您必须知道的一件事是您的查询返回的列数必须与您要插入的列数相匹配
"INSERT INTO NewTable(plan_name, plan_time)
SELECT cp.plan_name, cp.plan_time
FROM courses c
INNER JOIN course_to_plan cpl ON cpl.course_id = c.course_id
INNER JOIN courseplans cp ON cp.plan_id = cpl.plan_id
WHERE cpl.course_id = '$course_id'"
Warning: watch out for sql injection through
$course_id
.
请注意,我在 INSERT 语句中指定了 2 列,因为 SELECT 查询返回 2 列
如果表中的列数与查询返回的列数完全匹配,则无需指定列数。
关于php - MySQL根据SELECT查询结果插入多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10971653/