使用数组选择多行,然后INSERT到另一个语句

时间:2016-10-24 10:50:06

标签: php mysql

我正在尝试根据ID从一个表中选择数据,然后将返回的数据INSERT到另一个表中。

我的代码是:

<?php
    require '../../db-config.php';

    if(isset($_POST['course'])) {
        $selected_courses = '('. implode(',', $_POST['course']) .')';
        $status = 'Live';
        $active = 'Y';

        $stmt = "SELECT id, coursetitle FROM courses WHERE id IN ". $selected_courses ." 
                 AND status = ?";
        $stmt = $conn->prepare($stmt);
        $stmt->bind_param('i', $selected_courses);
        $stmt->execute();
        $stmt->bind_result($id, $coursetitle);

        while($stmt->fetch()) {
            $stmt = $conn->prepare("INSERT INTO distributor_course_settings
                                  (id, active, coursetitle) VALUES (?, ?, ?)");
            $stmt->bind_param("iss", $id, $active, $coursetitle);
            $stmt->execute();
        }
    }
?>
  

我得到的错误是:PHP致命错误:调用成员函数   布尔值

上的bind_param()

我的代码出了什么问题?

1 个答案:

答案 0 :(得分:0)

您可以在一个查询中执行这两个操作(选择和插入)。像这样:

INSERT INTO distributor_course_settings
(id, distributor, active, coursetitle) 
SELECT id, '$distributer', 'Y', coursetitle 
FROM courses 
WHERE id IN ". $selected_courses ." 
AND status = 'Live'

select语句中的值可以是字符串,php变量或子索引语句,如:

   INSERT INTO distributor_course_settings
    (id, distributor, active, coursetitle) 
    SELECT id, (select distributer from distributor_course_settings where id = 12), 'Y', coursetitle 
    FROM courses 
    WHERE id IN ". $selected_courses ." 
    AND status = 'Live' 

如果它是一个php变量,你的语句可能如下所示:

 $stmt = "INSERT INTO distributor_course_settings
    (id, distributor, active, coursetitle) 
    SELECT id, '".$distributor."', 'Y', coursetitle 
    FROM courses 
    WHERE id IN ". $selected_courses ." 
    AND status = 'Live'"