我有一个由 while 循环生成的动态表单,如下所示:
<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>
我试图将每个“response”和“question_id”插入到其自己的行中。我相信使用 forloop 来做到这一点是必要的,但无法弄清楚如何访问每个 POST 数组值:
$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();
提交到数据库的值为response_text的“Array”。如何访问每行的实际文本区域值?
最佳答案
$_POST['reponse_text']
是一个数组,像访问数组一样访问它。 token 匹配数错误是因为您在定义的参数之一上有 if/else 条件。
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
}
请务必将 execute()
放在 foreach 中,否则它将在整个过程之后执行,实际上仅插入已绑定(bind)到的最后一个响应文本查询。
关于php - 当输入是带有 PHP PDO 的数组时,从 $_POST 插入行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25025556/