我试图将表单值插入MySQL表,但表单是在while循环中,所以基本上我想添加多个值,我使用foreach但由于某些问题,只有前两个值被插入到表中其余的值要么丢失要么正确,我附加代码以及结果截图。
<?php
$i = 1;
$counter = 1;
while ($row = mysqli_fetch_array($questions)) {
?>
<div class="control-group">
<label class="control-label" for="focusedInput">(<?php echo $counter; ?>)
<?php
$questionid = $row['question_id'];
$question = $row['question'];
?>
<input type="hidden" name="questionid[]" value="<?php echo $questionid; ?>" />
<input type="hidden" name="question[]" value="<?php echo $question; ?>" />
<?php echo $row['question']; ?></label>
<div class="controls">
<?php
if ($row['answer_type'] == "Ratings") {
echo "
<p>
Low<input type='radio' name='rating$i' value='1' id='rating_0'>
<input type='radio' name='rating$i' value='2' id='rating_1'>
<input type='radio' name='rating$i' value='3' id='rating_2'>
<input type='radio' name='rating$i' value='4' id='rating_3'>
<input type='radio' name='rating$i' value='5' id='rating_4'>High
</p>
";
$i++;
} else if ($row['answer_type'] == "Comments") {
echo "<textarea name='answer[]' cols='' rows=''></textarea>";
}
echo "<br />";
$counter++;
?>
</div>
</div>
<?php } ?>
行动档案代码
foreach($_POST['questionid'] as $key=>$questionid){
$questionid = $_POST['questionid'][$key];
$answer = $_POST['answer'][$key];
$ratingKey = "rating".$key;
$rating = $_POST[$ratingKey];
$result3 = mysqli_query($con, "select question,answer_type from questions where question_id=$questionid;");
while($row = mysqli_fetch_array($result3)) {
$question = $row['question'];
$answer_type = $row['answer_type'];
if($answer_type == "Comments") {
$query2 = "insert into review_details (review_id,survey_id,question_id,question,answer_freeresponse) values(1,$_SESSION[surveyid],$questionid,'$question','$answer')";
$result2 = mysqli_query($con,$query2);
if(!$result2) {
echo mysqli_error($result2);
}
}
else if($answer_type == "Ratings") {
$query2 = "insert into review_details (review_id,survey_id,question_id,question,answer_rating) values(1,$_SESSION[surveyid],$questionid,'$question',$rating)";
$result2 = mysqli_query($con,$query2);
if(!$result2) {
echo mysqli_error($result2);
}
}
}
}
表格已提交
结果屏幕截图
答案 0 :(得分:1)
您应该在代码中的所有名称括号中添加$counter
,例如:"answer[]"
变为:"answer['.$counter.']"
。
"questionid[]"
是以另一种方式编写的,所以它是beocmes:"questionid[<?php echo $counter;?>]"
等等......
这将解决迭代数组的当前问题,但我建议检查并重写代码的所有。你的所有sql查询都是可以注入的......