Reputation: 2962
I have an array, which includes an insertId (as a key) several other values; this needs to be submitted as a $key=> $value array (e.g. 1 => 2, 1 =>3, 1=>5) etc.
However, when I bind the parameters within the foreach loop, I keep getting an array to string conversion error. as a result I get one row being inserted into the db (the correct key,and then a 0).
function instructorSubject()
{
$query = "INSERT into instructor_has_subject
SET instructor_id = :instructor_id,
subject_id = :id";
$last_id = $this->conn->lastInsertId();
$stmt = $this->conn->prepare($query);
//print_r($last_id);
//print_r($this->id);
if (isset($this->id) && $this->id != '') {
foreach ($_POST as $values) {
$stmt->bindParam(":instructor_id", $last_id, PDO::PARAM_INT);
$stmt->bindParam(":id", $this->id, PDO::PARAM_INT);
}
if($stmt->execute())
{
return true;
}
else
{
var_dump($stmt);
print_r($stmt->errorInfo());
return false;
}
}
}
A sample array is something like this: the insert id: 87 and then the second array appearing as a straight forward key=>value pair (for example:) ( [0] => 1 [1] => 3 )
I feel it has something to do with where I'm binding within the foreach. thanks in advance for any assistance.
Upvotes: 1
Views: 492
Reputation: 8621
After speaking to you in chat, this is the solution we came up with.
function instructorSubject()
{
$query = "INSERT INTO instructor_has_subject (instructor_id, subject_id) VALUES (?,?)";
$last_id = $this->conn->lastInsertId();
$stmt = $this->conn->prepare($query);
if(!empty($this->id)) {
foreach($_POST['subject_id'] as $id) {
$stmt->execute(array(
$last_id,
$id
));
}
}
}
The main thing we changed I believe was changing $_POST
to $_POST['subject_id']
.
We also removed bindParam
completely from the function, instead opting for unnamed parameters and passing the variables via execute()
inside the loop.
Upvotes: 2