当输入是带有PHP PDO的数组时,从$ _POST插入行

I have a dynamic form generated by a while loop that looks like this:

<form>
<?php while ($questions = $query->fetch(PDO::FETCH_ASSOC)) { ?>
<textarea name="reponse_text[]"></textarea>
<input type="hidden" name="question_id[]" value="<?php echo $questions['question_id']; ?>">
<?php } ?>
</form>

I am trying to insert each 'response' and 'question_id' into its own row. I believe using a forloop to do this is necessary but can't figure out how to access each POST array value:

$user_checkup_id = $db->lastInsertId();

$query = $db->prepare("INSERT INTO user_responses (user_response_text, question_id, user_checkup_id) 
VALUES (:user_response_text, :question_id, :user_checkup_id)");

foreach ($_POST as $key => $value) {

    $query->bindValue(':user_checkup_id', $user_checkup_id, PDO::PARAM_INT);

    if($key == "response_text") {
        $query->bindValue(':response_text', $value, PDO::PARAM_STR);
    } else if($key == "question_id") {
        $query->bindValue(':question_id', $value, PDO::PARAM_INT);
    }
}

$query->execute();

The value submitting to the database is "Array" for response_text. How do I access the actually text area value for each row?

$_POST['reponse_text'] is an array, access it like one. The match number of token error is because you have an if/else condition on one of the parameter being defined.

foreach ($_POST['reponse_text'] as $i => $value) {

    $query->bindValue(':user_checkup_id', $user_checkup_id, PDO::PARAM_INT);

    $query->bindValue(':response_text', $value, PDO::PARAM_STR);
    $query->bindValue(':question_id', $_POST['question_id'][$i], PDO::PARAM_INT);
    // here you do them at once or the other parameter won't be defined

    $query->execute(); // then you execute, for each different response text
}

be sure to put the execute() in the foreach or it will get executed after the whole thing, effectively only inserting the last response text having been bound to the query.

Try this:

foreach ($_POST["reponse_text"] as $key => $value) {

    $query->bindValue(':user_checkup_id', $user_checkup_id, PDO::PARAM_INT);

    if($key == "response_text") {
        $query->bindValue(':response_text', $_POST['reponse_text'][$key], PDO::PARAM_STR);
    } else if($key == "question_id") {
        $query->bindValue(':question_id', $_POST['question_id'][$key], PDO::PARAM_INT);
    }
}