1

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.

2
  • :questions_name != :question_name Commented Feb 16, 2016 at 18:36
  • @JayBlanchard thanks for the spot, I have changed that, the same error persists Commented Feb 16, 2016 at 18:38

1 Answer 1

2

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();
}
Sign up to request clarification or add additional context in comments.

3 Comments

Such a simple solution. No explanation needed really. Thank you!
@YourCommonSense That's bindValue bro. Do the second change and set bindParam.
Just realized that it was foolish edit that I made. Dunno what I were thinking of but it seems I was totally absent-minded. My apologies.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.