Reputation: 121
I have a form which allows multiple text boxes for users to add different question names, these are then passed to an array:
name="question_name[]
How do i go about inserting this array into my questions table using PDO and MySQL? I have tried:
$sql = "INSERT INTO questions (`question_name`) VALUES (:question_name)";
$stmt = $db->prepare($sql);
$stmt->bindValue(':question_name', $question_name);
$stmt->execute();
This gives me
Array to string conversion" error.
I have tested the print_r
statement and the results are as expected:
Array ( [0] => [Answer1] => [2] => [Answer2])
etc... depending on the amount of text boxes used.
I understand that it is to do with BindValues / BindParam / execute() statement I would just like a correct method that works and reasoning to help me learn. Thanks.
Upvotes: 1
Views: 4283
Reputation: 54831
Simple solution:
$sql = "INSERT INTO questions (`question_name`) VALUES (:question_name)";
// prepare a stamemnt only once
$stmt = $db->prepare($sql);
$stmt->bindParam(':question_name', $question_name);
// iterate over your POST[question_name] array
foreach ($_POST['question_name'] as $question_name) {
$stmt->execute();
}
Upvotes: 2