如何修复我的代码,使用php,mysql进行调查,在数组中保存3个值?

时间:2014-10-24 14:49:36

标签: php mysql arrays pdo survey

您好我正在尝试使用php和Mysql进行调查,下面的代码我保存每个问题的每个答案,但是当我尝试保存comments_per_questions时,它没有将该字段保存到数组中,它只保存一条注释。 / p>

如何修复此功能以保存到每个问题的数据库问题,答案和评论?

提前致谢。

数据库结构

"Questions" (idquestion, question)

"Surveys" (idsurvey, idquestion, answers, comments_per_question, survey_number)

此部分代码会从调查表中保存问题和答案。

public function NewSurveyMulti($answer = array())
{           
    if(!empty($answer)) {
        foreach($answer as $questi => $value  ) {
            $this->MyDB->Write("INSERT INTO surveys (`idquestion`, `answers`,`comments_per_questions` )
                    VALUES( 
                    '".$questi."', 
                    '".$value[0]."',
                    '".$_POST["comment"]."')");
        }
    }

survey_form.php

<?php
    // Fetch questions
    $cuestionario   =   $con->Fetch("SELECT * FROM questions"); ?>

    <form name="newDona" action="" method="post">
    </table><?php
    // Confirm there are questions being drawn from database
    $numrows        =   (is_array($cuestionario))? count($cuestionario): 0;
    if($numrows > 0) {
            // Loop through questions
            foreach($cuestionario as $row) { ?>
            <tr>
                <!-- Write the question -->
                <td><?php echo $row["question"];?></td>
            </tr>
            <th>
                <!-- Set the question id -->
                <select name="answer[<?php echo $row['idquestion']; ?>][]">
                    <option value=""></option>
                    <option value="1">yes</option>
                    <option value="no">NO</option>
                </select>
            </th><?php 


    <th><textarea type="text" name="comment" maxlength="50" cols="130" rows="5"/ ></textarea></th>


                     } ?>


<tr>
                <td colspan="5" align="center">
                    <input type="submit" name="send" id="send" value="SAVE" />
                </td>
            </tr>
        </table>
    </form>
    <?php } ?>

2 个答案:

答案 0 :(得分:0)

好的,现在问题显示循环中的注释字段,执行您对select所做的操作。

<textarea type="text" name="comment[<?php echo $row['idquestion']; ?>]" maxlength="50" cols="130" rows="5"/ >

并使用

在循环中收集它
$_POST["comment"][$questi]

ASIDE:您应prevent SQL injection,因为您的代码会使您的网站容易受到攻击。

答案 1 :(得分:0)

这是一个有效的例子:

<?php

echo '<form method="post">';
echo '<textarea name="comments[]" rows="8" cols="40"></textarea>';
echo '<textarea name="comments[]" rows="8" cols="40"></textarea>';
echo '<textarea name="comments[]" rows="8" cols="40"></textarea>';
echo '<button name="submit">Submit</button>';
echo '</form>';

if (isset($_POST['comments']))
{
    var_dump($_POST['comments']);
}