MySQL根据SELECT查询结果插入多行

Dav*_*vid 6 php mysql insert

我有这样的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';
Run Code Online (Sandbox Code Playgroud)

这将输出数据,例如:

+----------------------------+-----------+
| plan_name                  | plan_time |
+----------------------------+-----------+
| Plan number one name       |         6 |
| Plan number two name       |         6 |
| Plan number three name     |        10 |
+----------------------------+-----------+
Run Code Online (Sandbox Code Playgroud)

我希望将这些行插入表单提交的新表中.

如何继续编写代码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 */
Run Code Online (Sandbox Code Playgroud)

我不愿意承认我在PHP和MySQL中完全没用,但我正在努力学习.我想我必须创建某种数组来存储结果然后循环插入但我不知道如何.

cod*_*biz 14

您必须知道的一件事是查询返回的列数必须与要插入的列数相匹配

"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'"
Run Code Online (Sandbox Code Playgroud)

警告:注意sql注入$course_id.

请注意,我在INSERT语句中指定了2列,因为SELECT查询返回2列

如果表中的列数与查询返回的列数完全匹配,则无需指定列.