我目前正在使用codeigniter框架运行并遇到麻烦。我正在从数据库中检索问题列表和他们可能的答案列表(类似问卷)并将其加载到参与者尝试。
由于我正在使用的for循环,我无法更改个别问题的名称或ID值。我通过将questionID附加到name / id来解决这个问题。
当我把它发布到我的控制器上时,麻烦来了。当我需要将结果插回到数据库中时,我怎么能区分它?
<?php foreach($dbresult->result() as $row) {?>
<p><?php echo $row->Question ;?></p>
<?php if ($row->QuestionType == "MCQ"){ ?>
<ul>
<li><b>A: </b><?php echo $row->SelectionA; ?></li>
<li><b>B: </b><?php echo $row->SelectionB; ?></li>
<li><b>C: </b><?php echo $row->SelectionC; ?></li>
<li><b>D: </b><?php echo $row->SelectionD; ?></li>
</ul>
Select one of the following options:<br>
<input type="radio" name="<?php echo $row->QuestionID;?>.Ans" required value="A">A<br>
<input type="radio" name="<?php echo $row->QuestionID;?>.Ans" value="B">B<br>
<input type="radio" name="<?php echo $row->QuestionID;?>.Ans" value="C">C<br>
<input type="radio" name="<?php echo $row->QuestionID;?>.Ans" value="D">D<br>
<?php } elseif($row->QuestionType== "truefalse") {?>
Select one of the following options:<br>
<input type="radio" name="<?php echo $row->QuestionID;?>.Ans" value="true">True<br>
<input type="radio" name="<?php echo $row->QuestionID;?>.Ans" value="false">False<br>
<?php } else {?>
<input type="radio" name="<?php echo $row->QuestionID;?>.Ans" value="ok">OK<br>
<input type="radio" name="<?php echo $row->QuestionID;?>.Ans" value="agree">Agree<br>
<?php }?>
<?php } ?>
以上是我打印调查问卷的方式,任何可能的解决方案?
答案 0 :(得分:1)
很难管理这样的名字属性。
使用分组名称属性:
name="answers[<?php echo $row->QuestionID;?>]"
简单示例:
<?php foreach($dbresult->result() as $row) {?>
<p><?php echo $row->Question ;?></p>
<?php if ($row->QuestionType == "MCQ"){ ?>
<ul>
<li><b>A: </b><?php echo $row->SelectionA; ?></li>
<li><b>B: </b><?php echo $row->SelectionB; ?></li>
<li><b>C: </b><?php echo $row->SelectionC; ?></li>
<li><b>D: </b><?php echo $row->SelectionD; ?></li>
</ul>
Select one of the following options:<br>
<input type="radio" name="answers[<?php echo $row->QuestionID;?>]" required value="A">A<br>
<input type="radio" name="answers[<?php echo $row->QuestionID;?>]" value="B">B<br>
<input type="radio" name="answers[<?php echo $row->QuestionID;?>]" value="C">C<br>
<input type="radio" name="answers[<?php echo $row->QuestionID;?>]" value="D">D<br>
<?php } elseif($row->QuestionType== "truefalse") {?>
Select one of the following options:<br>
<input type="radio" name="answers[<?php echo $row->QuestionID;?>]" value="true">True<br>
<input type="radio" name="answers[<?php echo $row->QuestionID;?>]" value="false">False<br>
<?php } else {?>
<input type="radio" name="answers[<?php echo $row->QuestionID;?>]" value="ok">OK<br>
<input type="radio" name="answers[<?php echo $row->QuestionID;?>]" value="agree">Agree<br>
<?php }?>
<?php } ?>
因此,在PHP中,您可以通过其名称来调用它:
public function controller_name()
{
$answers = $this->input->post('answers');
foreach($answers as $question_id => $answer) {
}
}