Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /** database details */
- $dbHost = "localhost";
- $dbUser = "root";
- $dbPass = "";
- $dbName = "questionnaire";
- /** connect to database */
- if (!$dbLink = mysql_connect($dbHost, $dbUser, $dbPass)) {
- die(mysql_error());
- }
- /** select the database */
- if (!$dbSelected = mysql_select_db($dbName, $dbLink)) {
- die(mysql_error());
- }
- /**
- * Function to fetch all questions from the database.
- *
- * @return array
- */
- function fetchAllQuestions() {
- $results = mysql_query("
- SELECT *
- FROM questions
- ");
- while ($question = mysql_fetch_array($results)) {
- $questions[] = $question;
- }
- return $questions;
- }
- /**
- * Function to fetch available answers for specific question.
- *
- * @param int Question Id
- * @return array
- */
- function fetchAllAnswers($questionId) {
- $results = mysql_query("
- SELECT answers.answerid
- , answers.answer
- FROM answers as answers
- WHERE answers.questionid = $questionId
- ORDER
- BY answers.order
- ASC
- ");
- while ($answer = mysql_fetch_array($results)) {
- $answers[] = $answer;
- }
- return $answers;
- }
- ?>
- <h1>Example Site</h1>
- <?php if ($_POST['do'] == 'showanswers') : ?>
- <!-- show answers start -->
- <h2>Submitted Answers</h2>
- <ul>
- <?php foreach ($_POST['answers'] as $questionid => $answerid) : ?>
- <li>
- <strong>For questionid <?php echo $questionid; ?>, you select answerid <?php echo $answerid; ?></strong><br />
- insert into `user_answers` (`userid`, `questionid`, `answerid`) values (1, <?php echo $questionid; ?>, <?php echo $answerid; ?>);
- </li>
- <?php endforeach; ?>
- </ul>
- <br />
- <br />
- <!-- //show answers end -->
- <?php endif ; ?>
- <form action="questions.php" method="post">
- <input type="hidden" name="do" value="showanswers">
- <table border="1" cellpadding="6" width="70%">
- <?php foreach (fetchAllQuestions() as $question) : ?>
- <tr>
- <td><?php echo $question['question']; ?></td>
- <td>
- <select name="answers[<?php echo $question['questionid']; ?>]">
- <?php foreach(fetchAllAnswers($question['questionid']) as $answer) : ?>
- <option value="<?php echo $answer['answerid']; ?>"><?php echo $answer['answer']; ?></option>
- <?php endforeach; ?>
- </select>
- </td>
- </tr>
- <?php endforeach; ?>
- <tr>
- <td colspan="2">
- <input type="submit" name="submit" value="submit">
- </td>
- </tr>
- </table>
- </form>
- <?php mysql_close($dbLink);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement