Below is a form I am submitting once this form is submitted it will display a questionnaire. The hidden input type in the echo statement holds an array of question id's. the question text is printed out. Then a text box is created for the answer to be filled in and this will be passed through as an array of different answers - questionanswer[].

<form action="addanswers.php" method="post"> 
            <fieldset>
                <?php
                $sql = "SELECT * FROM QUESTIONS WHERE QUESTIONNAIRE_FK = '$questionnaireid';";
                $result = mysql_query($sql);

                while($row = mysql_fetch_array($result)) {
                $questionid = $row["QUESTION_ID"];

                if($row["QUESTION_TYPE"] == "ff"){

    echo "<input type='hidden' name = 'questionid[]' value = '".$questionid."'>".$row["QUESTION_TEXT"]." <input type='text' name='questionanswer[]''></br>";
            }
        }
        ?>
            <input type="Submit" value="Submit">
            </fieldset>
            </form>

I am then trying to submitting the data entered into the text box to the database but I also want to be able to link the question id from the form to the question answer and submit both of them to the answers table of the database along with a questionnaire id. The answers table looks like this:

Answers(Answer_ID(PK), Answer_Text, Question_FK, Questionnaire_FK)

Below shows addanswers.php. At the minute I am able to add the answer to the database which is posted from the text box in the questionnaire. I am having difficulty linking the question id to the answer text to submit it to the answer table.

$questionanswers = $_POST['questionanswer'];
$questionids = $_POST['questionid'];
foreach($questionanswers as $qa){
$sql = "INSERT INTO ANSWERS (ANSWER_TEXT, QUESTIONNAIRE_FK) values ('$qa', '$questionnaireid')";
mysql_query($sql) or die(mysql_error()); 
}

Any help and advice on this issue would be greatly appreciated.Thanks in advance for your help.

有帮助吗?

解决方案

Alright, I just wanted to make sure of your array structure, try this way:

$questionanswers = array_map('mysql_real_escape_string', $_POST['questionanswer']);
$questionids = array_map('mysql_real_escape_string', $_POST['questionid']);
foreach($questionanswers as $ind=>$ans){
$sql = "INSERT INTO ANSWERS (ANSWER_TEXT, QUESTIONNAIRE_FK) values ('$ans', '$questionids[$ind]')";
//$ind above contains index of the $questionanswers array-> 0, 1, 2 
//since your $questionids index is also numeric and have the
//same number of array values, we can use this index to refer 
//the corresponding $questionids
mysql_query($sql) or die(mysql_error()); 
}

Note:

Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top