多种选择PHP

时间:2016-02-16 05:36:07

标签: php mysql codeigniter

我用PHP(Codeigniter)和MySQL做了多项选择。我在尝试从每个问题的答案(带有动态名称)中检索值时遇到了麻烦。这是单选按钮的代码:

<input type="radio" name="question_id (according to id of question)" value="answer_id">

所以,如果我有3个随机问题,结构将是

<p>Question number 1 goes here</p>
<input type="radio" name="question_id1[]" value="1">
<input type="radio" name="question_id1[]" value="2">
<input type="radio" name="question_id1[]" value="3">
<input type="radio" name="question_id1[]" value="4">
<input type="radio" name="question_id1[]" value="5">


<p>Question number 6 goes here</p>
<input type="radio" name="question_id6[]" value="1">
<input type="radio" name="question_id6[]" value="2">
<input type="radio" name="question_id6[]" value="3">
<input type="radio" name="question_id6[]" value="4">
<input type="radio" name="question_id6[]" value="5">


<p>Question number 9 goes here</p>
<input type="radio" name="question_id9[]" value="1">
<input type="radio" name="question_id9[]" value="2">
<input type="radio" name="question_id9[]" value="3">
<input type="radio" name="question_id9[]" value="4">
<input type="radio" name="question_id9[]" value="5">

如何检索与问题相关的答案?例如,将它放在数组中,如:

array p = ['id_question' => 21, 'id_answer'=4]

The radio button structure

2 个答案:

答案 0 :(得分:0)

尝试

<p>Question number 9 goes here</p>
<input type="radio" name="question_id[9]" value="1">
<input type="radio" name="question_id[9]" value="2">
<input type="radio" name="question_id[9]" value="3">
<input type="radio" name="question_id[9]" value="4">
<input type="radio" name="question_id[9]" value="5">
<p>Question number 6 goes here</p>
<input type="radio" name="question_id[6]" value="1">
<input type="radio" name="question_id[6]" value="2">
<input type="radio" name="question_id[6]" value="3">
<input type="radio" name="question_id[6]" value="4">
<input type="radio" name="question_id[6]" value="5">

在服务器端

<?php
//assuming form method is post
$questions_array = array();
foreach($_POST[question_id] as $key=>$answer)
{
  $questions_array[] = array('id_question' => $key, 'id_answer'= $answer); 
}
print_r($questions_array);
?>

假设用户可以为单个问题选择单个单选按钮....

答案 1 :(得分:0)

我已将代码放在表单中,并提交了提交按钮。然后输出我得到它 排列 (     [question_id1] =&gt;排列         (             [0] =&gt; 3         )

[question_id6] => Array
    (
        [0] => 2
    )

[question_id9] => Array
    (
        [0] => 3
    )

[submit] => submit

) 所以我们可以使用相同的名称访问。我用普通的PHP代码做到了。因为形成的数组在核心php和codeigniter中都是相同的。所以我们通常可以使用for循环访问它。