user6618037 user6618037 - 1 month ago 5
MySQL Question

SELECTING Multiple Rows with an Array and then INSERT to another statement

I am trying to SELECT data from one table based on the ID and then INSERT the returned data in to another table.

My code is:

<?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();
}
}
?>



The error I am getting is: PHP Fatal error: Call to a member function
bind_param() on boolean


What is wrong with my code?

Answer

you can perform both actions (select and insert) in one query. Something like this:

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