PHP - Help With Correcting Php Quiz
Could anyone help me please. I am trying to create a quiz in (quiz.php) which is works fine, but when I am trying to correct the quiz in another page (result.php) I had an error. I think the problem with posted answers and I couldn't solve it.
This is my code in (quiz.php):
<form method="post" action="result.php"> <?php session_start(); $questionNumber = 1; $query = mysql_query("SELECT * FROM Question WHERE TID = 'TEST' order by RAND()"); while ($result = mysql_fetch_array($query)) { ?> <?php echo $questionNumber . ") " . $result['Question'] . "<br>"; ?> <input type="radio" name="answer<?php echo $result["QID"] ?>" value="A"> <?php echo $result['A']; ?> <br> <input type="radio" name="answer<?php echo $result["QID"] ?>" value="B"> <?php echo $result['B']; ?> <br> <input type="radio" name="answer<?php echo $result["QID"] ?>" value="C"> <?php echo $result['C']; ?> <br> <input type="radio" name="answer<?php echo $result["QID"] ?>" value="D"> <?php echo $result['D']; ?> <br> <?php $questionNumber +=1; } ?> <input type="submit" name="checkQuiz" value="Check Quiz" onclick="location.href='result.php'" /> </form>And This is my code in (result.php): <?php if(isset($_POST['checkQuiz'])) { $correctAnswers = 0; $wrongAnswers = 0; $idList = join (',', array_map('intval', array_keys($_POST['answer']))); $sql = "SELECT QID, Answers FROM correct WHERE QID IN ($idList)"; while (list($QID, $correct) = mysql_fetch_row($res)) { if ($correct == $_POST['answer'][$QID]) { $correctAnswers +=1; } else { $wrongAnswers +=1; } } } ?> // in the body <?php $numberOfQs = $correctAnswers + $wrongAnswers; $score = round(($correctAnswers / $numberOfQs) * 100); ?> Correct Answers: <?php echo $correctAnswers; ?> <br> Wrong Answers: <?php echo $wrongAnswers; ?> <br> Sco <?php echo $score; ?> Similar TutorialsHi guys, First time post here so go easy on me OK, heres the deal: I have a page with a form and when submitted it needs to update MySQL tables The code for the form is as follows: Code: [Select] <form method="post" action="update.php"> <select name="Batsman"> <option value="Player 1">Player 1</option> <option value="Player 2">Player 2</option> </select> <input type="text" name="Runs" size="5" /> <input type="text" name="Overs" size="5" /> <input type="submit" value="Submit Batting Scores" /> </form> The code for the 'update.php' is as follows: Code: [Select] <?php $Batsman = $_POST['Batsman']; $Runs = $_POST['Runs']; $Overs = $_POST['Overs']; mysql_connect ("HOST", "*USERNAME*", "*PASSWORD*") or die ('error: ' .mysql_error()); mysql_select_db ("DB_NAME"); $query="UPDATE batting SET runs = ("'.$Runs.'"+runs) WHERE batsman = '$Batsman' " $query2="UPDATE bowling SET overs = ("'.$Overs.'"+overs) WHERE batsman = '$Batsman' " mysql_query($query) or die ('Error updating result: ' .mysql_error()); mysql_query($query2) or die ('Error updating result: ' .mysql_error()); echo "Results updated with: ".$Batsman." - ".$Runs." Runs" ; ?> The database layout is: 2 tables, 1 named "batting" another named "bowling" What the form SHOULD be doing is: Take what ever number is inputed to "Runs" and ADD TO THE CURRENT TOTAL of 'Runs' in 'Batting' Take what ever number is inputed to "Overs" and ADD TO CURRENT TOTAL of 'Overs' in 'bowling' The IDs on each table are 'Player 1' and 'Player 2' - labeled on each table as 'batsman' The corresponding 'batsman' is selected on the form via the drop down before submiting. For example if 'Player 2' currently has 50 'runs' in 'batting' and 10 'Overs' in 'bowling', and I then select him on the drop down and input 10 runs and 1 over, when I hit submit his data in the MySQL tables SHOULD go to 60 'runs' in 'batting' and 11 'overs' in 'bowling' Im hoping labeling the table data in this way provides a clear enough explanation of the set up with out the need to know about the subject matter in hand, (cricket, if you havent guessed already ) Now the table worked fine when I was updating to REPLACE the numbers in 'runs' or 'overs' but I need it to ADD to the existing number I was advised else where to add the '+runs' '+overs' in order to get this to work but all Im getting is an error. The current error coming back is: Quote Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in /home/a2552500/public_html/update.php on line 10 If someone can correct me whereever I am going wrong that would be great, however an explination to acompany any correction would be appreciated as Id like to learn what is wrong, why its wrong and how to fix it. Thanks in advance for your time Tom The following script comes from create a decorator example. Please take a look at __construct() and $pathItem. Doesn't look like any PHP I've ever seen. Agree? I don't think it matters and just stating so to make sure, but I am not using a docket but have api-platform on the local server. I've gotten all to work until now. <?php // api/src/OpenApi/JwtDecorator.php declare(strict_types=1); namespace App\OpenApi; use ApiPlatform\Core\OpenApi\Factory\OpenApiFactoryInterface; use ApiPlatform\Core\OpenApi\OpenApi; use ApiPlatform\Core\OpenApi\Model; final class JwtDecorator implements OpenApiFactoryInterface { public function __construct( private OpenApiFactoryInterface $decorated ) {} public function __invoke(array $context = []): OpenApi { $openApi = ($this->decorated)($context); $schemas = $openApi->getComponents()->getSchemas(); $schemas['Token'] = new ArrayObject([ 'type' => 'object', 'properties' => [ 'token' => [ 'type' => 'string', 'readOnly' => true, ], ], ]); $schemas['Credentials'] = new ArrayObject([ 'type' => 'object', 'properties' => [ 'email' => [ 'type' => 'string', 'example' => 'johndoe@example.com', ], 'password' => [ 'type' => 'string', 'example' => 'apassword', ], ], ]); $pathItem = new Model\PathItem( ref: 'JWT Token', post: new Model\Operation( operationId: 'postCredentialsItem', responses: [ '200' => [ 'description' => 'Get JWT token', 'content' => [ 'application/json' => [ 'schema' => [ '$ref' => '#/components/schemas/Token', ], ], ], ], ], summary: 'Get JWT token to login.', requestBody: new Model\RequestBody( description: 'Generate new JWT Token', content: new ArrayObject([ 'application/json' => [ 'schema' => [ '$ref' => '#/components/schemas/Credentials', ], ], ]), ), ), ); $openApi->getPaths()->addPath('/authentication_token', $pathItem); return $openApi; } } I am thinking that maybe the constructor needs to be changed to: private $decorated; public function __construct(OpenApiFactoryInterface $decorated) { $this->decorated = $decorated; } Regarding $pathItem, Model\PathItem's constructor is as follows. Any thoughts on what they are suggesting? Thanks public function __construct( string $ref = null, string $summary = null, string $description = null, Operation $get = null, Operation $put = null, Operation $post = null, Operation $delete = null, Operation $options = null, Operation $head = null, Operation $patch = null, Operation $trace = null, ?array $servers = null, array $parameters = [] ) {/* ... */}
Edited January 28 by NotionCommotion Not using docket Hello. I try to write a simple multiple choice quiz. I have my questions and answers in a xml file and I read the file into an array. My main problems is how I'll connect the various sessions where the different questions appear in order to keep the score and sum it up in the end. Also, how do I check if the selected answer is correct or not? Assuming that the correct answers are in an array in php code, can I use javascript to check the answers? Any help? Thanks. Hey guys,
I'm making php quiz, but got some problems with results getting - they are all wrong. Here is the db table for it.
CREATE TABLE IF NOT EXISTS `quiz` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `question` text COLLATE utf8_unicode_ci NOT NULL, `answer1` text COLLATE utf8_unicode_ci NOT NULL, `answer2` text COLLATE utf8_unicode_ci NOT NULL, `answer3` text COLLATE utf8_unicode_ci NOT NULL, `correctanswer` text COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`), KEY `pollid` (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=34 ;And script itself. $questionNumber = 1; $query = sql_query("SELECT * FROM quiz ORDER BY RAND() LIMIT $limit"); while ($result = mysqli_fetch_array($query)) { ?> <div class="padding"> <p> <?php echo "<b><h4>" . $questionNumber . ") " . $result['question'] . "</h4><br></b>"; ?> <input type="radio" name="answer[<?php echo $result['id'] ?>]" value=""> <?php echo $result['answer1']; ?> <br> <input type="radio" name="answer[<?php echo $result['id'] ?>]" value=""> <?php echo $result['answer2']; ?> <br> <input type="radio" name="answer[<?php echo $result['id'] ?>]" value=""> <?php echo $result['answer3']; ?> <br> </p> <hr> </div> <?php $questionNumber +=1; } $correctAnswers = 0; $wrongAnswers = 0; $questions = ''; $idList = join (',', array_map('intval', array_keys($_POST['answer']))); $sql = "SELECT id, question, answer1, answer2, answer3, correctanswer FROM quiz WHERE id IN ($idList)"; $res = sql_query($sql) ; $qno = 1; while (list($id, $q, $a, $b, $c, $correct) = mysqli_fetch_row($res)) { if ($correct == $_POST['answer'][$id]) { $correctAnswers +=1; } else { $wrongAnswers +=1; } } echo $correctAnswer; echo $wrongAnswers; ?>Help me guys! can anyone please tell me how can I make a quiz in php which displays random questions one at a time
Hey all! I am new to these forums, but this seems like a really good place for information. I am a beginner in PHP coding, so I don't have that much experience with how to do quite simple tasks. I have a job to fulfill and I have to create a personality quiz, which basically means a user answers about eight questions with three choices and then he will be dubbed as one of six different personalities. I've tired doing this, believe me, but I just don't get it to work. Are there any websites, downloads, or words of advice you guys could give me? And no, I will not be using one of those quiz generators online; it should be made from raw code. Thank you so much! Hey, I want to start by saying this is the first time I've ever looked at PHP. I'm using a Wordpress plugin from http://www.netconcepts.com/wordpress-quiz-plugin/ The user answers a few questions, and based off that, they get a results sheet with their personality type. The only issue is that none of the line breaks that I've used in the results show up. It's just one big paragraph (even when in the editing stage, I've made it look all nice). There's no plugin support for this. I think it has something to do with this file maybe... "<?php /* Copyright (c) 2007 Andrew Shell (http://blog.andrewshell.org) and Netconcepts (http://www.netconcepts.com) WordPress Quiz Plugin is released under the GNU General Public License (GPL) http://www.gnu.org/licenses/gpl.txt */ class WQP_Factory { function add_quiz_type($type, $typename, $classname, $classpath) { if (!isset($GLOBALS['WQP_Factory']['QUIZ_TYPES']) || !is_array($GLOBALS['WQP_Factory']['QUIZ_TYPES'])) { $GLOBALS['WQP_Factory']['QUIZ_TYPES'] = array(); } $GLOBALS['WQP_Factory']['QUIZ_TYPES'][$type] = array( 'type' => $type, 'typename' => $typename, 'classname' => $classname, 'classpath' => $classpath ); } function get_quiz_types() { if (!isset($GLOBALS['WQP_Factory']['QUIZ_TYPES']) || !is_array($GLOBALS['WQP_Factory']['QUIZ_TYPES'])) { $GLOBALS['WQP_Factory']['QUIZ_TYPES'] = array(); } return $GLOBALS['WQP_Factory']['QUIZ_TYPES']; } function by_id($quiz_id) { require_once dirname(__FILE__) . "/wqp-quiz.php"; global $wpdb; $quiz_id = intval($quiz_id); $sql = "SELECT * FROM " . $wpdb->wqp_quizzes . " WHERE quiz_id = {$quiz_id} LIMIT 1"; $row = $wpdb->get_row($sql); $quiz_type = strtolower($row->quiz_type); $quiz_types = WQP_Factory::get_quiz_types(); if (empty($quiz_type)) { return null; } elseif (!isset($quiz_types[$quiz_type])) { die("Invalid Quiz Type: {$quiz_type}"); } $quiz_class = $quiz_types[$quiz_type]['classname']; $quiz_file = $quiz_types[$quiz_type]['classpath']; require_once $quiz_file; $quiz = new $quiz_class($row->quiz_id); $data = unserialize($row->quiz_data); $quiz->assign_all($data); return $quiz; } function by_type($quiz_type) { require_once dirname(__FILE__) . "/wqp-quiz.php"; $quiz_type = strtolower($quiz_type); $quiz_types = WQP_Factory::get_quiz_types(); if (!isset($quiz_types[$quiz_type])) { die("Invalid Quiz Type: {$quiz_type}"); } $quiz_class = $quiz_types[$quiz_type]['classname']; $quiz_file = $quiz_types[$quiz_type]['classpath']; require_once $quiz_file; $quiz = new $quiz_class(); $quiz->assign_defaults(); return $quiz; } } if (!function_exists('scandir')) { function scandir($directory, $sorting_order = 0) { if (!is_string($directory)) { user_error('scandir() expects parameter 1 to be string, ' . gettype($directory) . ' given', E_USER_WARNING); return; } if (!is_int($sorting_order) && !is_bool($sorting_order)) { user_error('scandir() expects parameter 2 to be long, ' . gettype($sorting_order) . ' given', E_USER_WARNING); return; } if (!is_dir($directory) || (false === $fh = @opendir($directory))) { user_error('scandir() failed to open dir: Invalid argument', E_USER_WARNING); return false; } $files = array (); while (false !== ($filename = readdir($fh))) { $files[] = $filename; } closedir($fh); if ($sorting_order == 1) { rsort($files); } else { sort($files); } return $files; } } // Escape output string function wqp_escape_string($value) { $escaped = $value; $escaped = wp_specialchars($escaped, true); return $escaped; } // Filter input string function wqp_filter_string($value) { $filtered = $value; $filtered = strip_tags($filtered); $filtered = stripslashes($filtered); return $filtered; } function wqp_safe_array(&$value, $default_value = array()) { if (!isset($default_value) || !is_array($default_value)) { $default_value = array(); } return (isset($value) && is_array($value) ? $value : $default_value); } function wqp_safe_value(&$value, $default_value = '') { return (isset($value) ? $value : $default_value); } function wqp_the_content($content) { preg_match_all( '!\[quiz=([0-9]+)\]!isU', $content, $matches ); foreach (array_keys($matches[0]) as $i) { $quiz = WQP_Factory::by_id($matches[1][$i]); if (!empty($quiz) && is_object($quiz)) { if (isset($_POST['answer']) && is_array($_POST['answer'])) { $content = str_replace($matches[0][$i], $quiz->fetch_answer($_POST['answer']), $content); } else { $content = str_replace($matches[0][$i], $quiz->fetch_quiz(), $content); } } } return $content; } function wqp_the_title($title) { preg_match_all( '!\[quiz=([0-9]+)\]!isU', $title, $matches ); foreach (array_keys($matches[0]) as $i) { $quiz = WQP_Factory::by_id($matches[1][$i]); if (!empty($quiz) && is_object($quiz)) { $title = str_replace($matches[0][$i], $quiz->get_title(), $title); } } return $title; } function wqp_get_query_template($template_dir, $type) { $template = ''; if (file_exists(TEMPLATEPATH . "/{$type}.php")) { $template = TEMPLATEPATH . "/{$type}.php"; } elseif (file_exists($template_dir . "/{$type}.php")) { $template = $template_dir . "/{$type}.php"; } return apply_filters("wqp_{$type}_template", $template); } function wqp_fetch_template($template_dir, $type, $params = null) { if (!empty($params) && is_array($params)) { extract($params); } $template = wqp_get_query_template($template_dir, $type); if (file_exists($template)) { ob_start(); include($template); $contents = ob_get_contents(); ob_end_clean(); } else { $contents = ''; } return $contents; } function wqp_plugins_loaded() { WQP_Factory::add_quiz_type('personality', 'Personality', 'WQP_Quiz_Personality', dirname(__FILE__) . '/quizzes/personality.php'); do_action('wqp_register_quiz_types');" I might have to add an nlbr somewhere or something??? Let me know how to proceed. Thanks!!! " Hello every body. Currently I am creating a quiz section but I'm facing some problem.
The thing i want is that the questions which the user has played before should not come again.
So here is my quiz table.
+-------------+-------------------------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+-------------------------------------+------+-----+---------+----------------+ | qid | int(11) | NO | PRI | NULL | auto_increment | | questions | varchar(255) | NO | UNI | NULL | | | correct_ans | varchar(50) | NO | | NULL | | | option1 | varchar(50) | NO | | NULL | | | option2 | varchar(50) | NO | | NULL | | | option3 | varchar(50) | NO | | NULL | | | category | enum('Maths','Bollywood','Special') | NO | | NULL | | +-------------+-------------------------------------+------+-----+---------+----------------+Then I have created another tablle where I stored their user id and the questions Iid they have played. Here is the table. +----------------+---------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------------+---------+------+-----+---------+-------+ | mid | int(11) | NO | PRI | NULL | | | quiz_questions | text | NO | | NULL | | +----------------+---------+------+-----+---------+-------+In the above table, the ids are stored in this pattern 1,5,10,6,7,11,15,29,2 ------------------> Tis are the quiz id. I'm using this query but to bring the uinque questions but still the same questions are comming.. $q = $this->database()->prepare("SELECT quiz_questions FROM quiz_played WHERE mid = ?"); $q->bindParam(1, $mid,PDO::PARAM_INT); $q->execute(); $row = $q->fetch(PDO::FETCH_ASSOC); $q->closeCursor(); $q1 = $this->database()->prepare("SELECT * FROM quiz WHERE qid NOT IN (?) ORDER BY RAND()"); $q1->bindParam(1, $genre,PDO::PARAM_STR); $q1->bindParam(1, $row['quiz_questions'], PDO::PARAM_STR); $q1->execute(); return $q1->fetch(PDO::FETCH_ASSOC);Any help will be really appreciated. I've made a code here.. It can create a quiz. It consist of a question and a 4 choices.. But my problem here is. when i inserted only 2 values for the choices, there would still be 4 radio button(Choices). Can someone help me. i want my code to be like : When user inputs 4 values. there would be 4 choices, but when user insert 2 values, there would be 2 values.. Here's my code for the form Code: [Select] <form name="formupload" method="post" action="setdate.php"> <div id="apDiv10"><input type="image" src="images/setdate.png" name="Image9" width="170" height="35" border="0" ></div> </form><form name="formupload" method="post" action="valdeactiveass.php"> <div id="apDiv8"><input type="image" src="images/deacass.png" name="Image9" width="170" height="35" border="0" ></div> </form><form name="formupload" method="post" action="valactiveass.php"> <div id="apDiv7"><input type="image" src="images/activeass.png" name="Image9" width="170" height="35" border="0" ></div> </form><form name="formupload" method="post" action="quiz_preview.php"> <div id="apDiv3"><input type="image" src="images/preview.png" name="Image9" width="170" height="35" border="0" ></div> </form> <form name="form2" method="post" action="delques.php"> <div id="apDiv9"><input type="image" src="images/delques.png" name="Image8" width="170" height="35" border="0" ></div> </form><form name="formupload" method="post" action="validatequiz.php"> <input type="text" style="position:absolute; top:160px; left:101px; width: 576px; height: 31px; font-size:10px;" name="question" id="question" /> <input type="text" style="position:absolute; top:244px; left:109px; width: 567px; height: 19px; font-size:10px;" name="c1" id="c1" /> <input type="text" style="position:absolute; top:297px; left:108px; width: 567px; height: 19px; font-size:10px;" name="c2" id="c2" /> <input type="text" style="position:absolute; top:350px; left:109px; width: 567px; height: 19px; font-size:10px;" name="c3" id="c3" /><input type="text" style="position:absolute; top:396px; left:110px; width: 567px; height: 19px; font-size:10px;" name="c4" id="c4" /> <select style="position:absolute; top:463px; left:309px; width: 80px; height: 23px; font-size:10px;" name="answer" id="answer"> <option value="Select">Select</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select><div id="apDiv2"><input type="image" src="images/submit.png" name="Image8" width="170" height="35" border="0" ></div> </form> And this of the quiz maker.. Code: [Select] <?php if (isset($_POST['sent'])) { for ($i=0;$i<count($questions);$i++) { if ($_POST['q2'.$i]=="w") { $score++; } else { } } $percent = number_format(($score/count($questions))*100,2,".",","); echo("<br>".$score." out of ".count($questions)." (".$percent."% right)<br>\n"); } else { echo("<form action=\"#\" method=\"post\">\n"); echo("<input type=\"hidden\" name=\"sent\">\n"); for ($i=0;$i<count($questions);$i++) { echo("<b>".$questions[$i][0]."</b><br><br>\n"); if ($questions[$i][5]==1) { echo("<input type=\"radio\" name=\"q2".$i."\" value=\"c\"> ".$questions[$i][1]."<br>\n"); } else { echo("<input type=\"radio\" name=\"q2".$i."\" value=\"w\"> ".$questions[$i][1]."<br>\n"); } if ($questions[$i][5]==2) { echo("<input type=\"radio\" name=\"q2".$i."\" value=\"c\"> ".$questions[$i][2]."<br>\n"); } else { echo("<input type=\"radio\" name=\"q2".$i."\" value=\"w\"> ".$questions[$i][2]."<br>\n"); } if ($questions[$i][5]==3) { echo("<input type=\"radio\" name=\"q2".$i."\" value=\"c\"> ".$questions[$i][3]."<br>\n"); } else { echo("<input type=\"radio\" name=\"q2".$i."\" value=\"w\"> ".$questions[$i][3]."<br>\n"); } if ($questions[$i][5]==4) { echo("<input type=\"radio\" name=\"q2".$i."\" value=\"c\"> ".$questions[$i][4]."<br><br>\n"); } else { echo("<input type=\"radio\" name=\"q2".$i."\" value=\"w\"> ".$questions[$i][4]."<br><br>\n"); } } echo("<input type=\"submit\" value=\"Submit Exam\"></form>"); } ?> Hi all, Can anyone offer assistance with the following: I am trying to obtain a score from a users radio button selection on a simple quiz. i am not able to obtain the results.... Hello, I am trying to build a quiz with PHP and MySQL. I have successfully managed to build the database and display the questions from the database. I have also managed to get the radio button to individually map to each question (rather than seeing all questions with one possible answer). What I have been unable to do (for some days now) is to match the correct radio button with the answer (all say incorrect at the moment even if you answer correctly.) Any help would be greatly appreciated. Code below questions.php Code: [Select] <?php require_once('connectvars1.php'); //Connect to the database $dbc = mysqli_connect(DB_Host, DB_User, DB_Password, DB_Name); $query = "SELECT * FROM questions"; $result = mysqli_query($dbc, $query); // if records are present if (mysqli_num_rows($result) > 0) { $row = mysqli_fetch_array($result); if (mysqli_num_rows($result) > 0) { // print answer list as check boxes while ($row = mysqli_fetch_array($result)) { $id = $row['autokey']; $quest = $row['q_text']; $option1 = $row['op1']; $option2 = $row['op2']; $option3 = $row['op3']; $option4 = $row['op4']; $answer= $row['answer']; echo "$quest"; ?> <br /> <input type= radio name= <?php echo "$id" ?> <value="A"/>A. <?php echo "$option1" ?><br /> <input type= radio name= <?php echo "$id" ?> <value="B"/>B. <?php echo "$option2" ?><br /> <input type= radio name= <?php echo "$id" ?> <value="C"/>C. <?php echo "$option3" ?><br /> <input type= radio name= <?php echo "$id" ?> <value="D"/>D. <?php echo "$option4" ?><br /> <br /> <?PHP } ?> <br /> <div align="center"><input type="submit" name="btn_submit" value="Submit Answers" /></div> <input type="hidden" name="submitted" value="TRUE" /> </form> <?php } echo '</form>'; } mysqli_close($dbc); ?> score.php Code: [Select] <?php // Check answers if((isset($_POST['$id'])) && ($_POST['$id'] == "$answer")){ echo 'Your answer was correct for q1!'; }else{ echo 'Your answer was incorrect for q1.'; } ?> <br /> <?php if((isset($_POST['$id'])) && ($_POST['$id'] == "$answer")){ echo 'Your answer was correct for q2!'; }else{ echo 'Your answer was incorrect for q2.'; } ?> i want online quiz in php mysql Hi people. I'm building a quiz with one correct answer out of possible 4. My problem is that after I choose a random answer (which is the correct one) I have problems with choosing random 3 wrong answers which are not the same as answer 1 (they all come from the same table). My first mysql query gives me back 1 row my second mysql query gives me back 15 row (there were 16 - 1 which is the correct one). How can take only 3 rows out of that second query and output them into variables that I can later echo into a form? Can you help me understand this problem or can you propose an alternative method to deal with this? Here are my two queries: Code: [Select] // Fetch random answer (correct) $query = "SELECT * FROM psychofarm_brand WHERE `id`=".$randomNumber; $result = mysql_query($query); $row = mysql_fetch_array($result); // Fetch wrong answer $query2 = "SELECT * FROM psychofarm_gen WHERE `id`!=".$randomNumber; $result2 = mysql_query($query2); $row2 = mysql_fetch_array($result2); I hope this is clear. Thanks Hello everyone, I have a datatbase containing fields id, question, answer, and type. The questions are in true/false format, multiple choice and fill in the blank(text). At the moment, I am only trying to get the true and false questions to work. My code is as follows Code: [Select] <?php $connection = mysql_connect("localhost","root","root") or die("couldn't connect"); $select = mysql_select_db("login") or die ("cannot select database!"); $query = mysql_query("SELECT * FROM questions"); $numrows = mysql_num_rows($query); if ($numrows!=0) { //code to login while($row = mysql_fetch_assoc($query)) { $dbquestion = $row['question']; $dbanswer = $row['answer']; $dbtype = $row['type']; $dbid = $row['id']; $correctanswer = explode('|',"$dbanswer"); switch($dbtype){ case "mchoice": echo"<br/>"; echo $dbquestion; echo"<br/>"; break; case "boolean": echo"<br/>"; echo $dbquestion; echo"<br/>"; echo $correctanswer[0]; //display radio buttons ?> <form name="boolean" method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>"> True <input name="question" type="radio" value= "True" /> False <input name="question" type="radio" value= "False" /> <input name="id" input type="hidden" value="<?php $dbid ?>" /> <input type="submit" name="submit" id="submit" value="Submit" /> <?php echo "The answer submitted was "; echo $_POST['question']; ?> <?php break; case "text": echo"<br/>"; echo $dbquestion; echo"<br/>"; //display text box break; } } } ?> The problem I'm having is that this creates a submit button for each question. When choosing true or false for the answer and pressing submit, the answer is selected for every question. I need the code to look at what the user has entered, check the answer against correctanswer[0]. I'm really in a bit of a hole here and if anyone can help me it would be greatly appreciated. Many thanks in advance James Ok this is kind of a logical help which I need. I am writing a quiz script and I need to send and receive data from database on a timeout basis and I also want that when time finishes (of quiz) user must be moved to some other page. I basically need timeout based function if there are any and real time retrieval and storage of data. Thanks a lot Hi guys. I have a quiz and everything works fine now but what im trying to figure out is, if there is a way to submit each question and get the results there and then rather than using sessions and getting a final quiz results page. Hope this can be done. The code i use is attached. For example. the user will answer q1 but then submit each question rather than all at once and then get feedback after each question. Thanks for all your help guys Lance Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>Forensics E-learning Package</title> <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body> <div id="wrapper"> <div id="header"> <div id="toplinks"> </div> </div> <div id="menu"> <ul> <li><a class="selected" href="home.html">Home</a></li> <li><a href="initialquiz.php">Initial Quiz</a></li> <li><a href="about.php">About</a></li> </ul> </div> <div id="content"> <div id="main"> <h1>Initial Quiz</h1><BR /> <form name="Forensics Test" method="post" action="detection.php"> <h1>Protection</h1> <hr /> <b>1. What does an IDS do? <BR /><BR /></b> <UL> <? if($attempted == true && !isset($q1)) { echo 'bgcolor="#FFFFCC"'; } ?> <input type="radio" name="q1" id="q1a" value="1" />An IDS evaluates a suspected intrusion once it has taken place and signals an alarm<BR><? if($q1 == "1"){echo "checked=\"checked\"";} ?> <input type="radio" name="q1" id="q1b" value="2">An IDS blocks intrusions before it happens and signal an alarm<BR><? if($q1 == "1"){echo "checked=\"checked\"";} ?> <input type="radio" name="q1" id="q1c" value="3">An IDS blocks all intrusions before it happens and monitors the network, however does not signal an alarm.<BR><? if($q1 == "1"){echo "checked=\"checked\"";} ?></UL><hr /> <b>2. What does a Firewall do?<BR /><BR></b> <UL> <? if($attempted == true && !isset($q2)) { echo 'bgcolor="#FFFFCC"'; } ?> <input type="radio" name="q2" id="q2a" value="1">Firewalls limit access once the intrusion is within a network and then signals an alarm.<BR><? if($q2 == "1"){echo "checked=\"checked\"";} ?> <input type="radio" name="q2" id="q2b" value="2">Firewalls limit access between networks to prevent intrusion and do not signal an attack.<BR><? if($q2 == "1"){echo "checked=\"checked\"";} ?> <input type="radio" name="q2" id="q2c" value="3">Firewalls limit access to a network and prevent all intrusions. An alarm to the user is raised.<br><? if($q2 == "1"){echo "checked=\"checked\"";} ?></UL><hr /> <p><b>3. What does Tripwire do?</b> </p> <UL> <? if($attempted == true && !isset($q3)) { echo 'bgcolor="#FFFFCC"'; } ?> <input type="radio" name="q3" id="q3a" value="1">Tripwire does not protect from intrusions however signals an alarm to the user that network intrusions are occurring.<BR><? if($q3 == "1"){echo "checked=\"checked\"";} ?> <input type="radio" name="q3" id="q3b" value="2">Tripwire does not perform system integrity checks in terms of file change, however does prevent access to a network unless otherwise stated.<BR><? if($q3 == "1"){echo "checked=\"checked\"";} ?> <input type="radio" name="q3" id="q3c" value="3">Tripwire helps identify changes in files. Tripwire records a set of information about all the important files in your server in case of a change.</p><? if($q3 == "1"){echo "checked=\"checked\"";} ?> <BR> </UL><hr /> <p><b>4. What type of files does a traditional anti-virus protect you from?</b> </p> <UL> <? if($attempted == true && !isset($q4)) { echo 'bgcolor="#FFFFCC"'; } ?> <input type="radio" name="q4" id="q4a" value="1">Viruses and tracking cookies<BR><? if($q4 == "1"){echo "checked=\"checked\"";} ?> <input type="radio" name="q4" id="q4b" value="2">Rootkits and Viruses<BR><? if($q4 == "1"){echo "checked=\"checked\"";} ?> <input type="radio" name="q4" id="q4c" value="3">Worms and Rootkits<BR><? if($q4 == "1"){echo "checked=\"checked\"";} ?> </UL><hr /> <p><b>5. What does an Anti-root kit protect you from?</b> </p> <UL> <? if($attempted == true && !isset($q5)) { echo 'bgcolor="#FFFFCC"'; } ?> <input type="radio" name="q5" id="q5a" value="1">Anti-rootkit protects from only viruses, key loggers and backdoors.<BR><? if($q5 == "1"){echo "checked=\"checked\"";} ?> <input type="radio" name="q5" id="q5b" value="2">Anti-rootkit protects from viruses, backdoors, spyware and key loggers as a collection.<BR><? if($q5 == "1"){echo "checked=\"checked\"";} ?> <input type="radio" name="q5" id="q5c" value="3">Anti-rootkit protects from only viruses and backdoors.<BR><? if($q5 == "1"){echo "checked=\"checked\"";} ?> </UL> <HR><BR /><BR /> <input type="submit" value="Go to Next Section" /> </form> </div> <div id="right"> <h2>Right Menu</h2> <div class="rightitem"> <ul> <li><a class="selected" href="home.html">Home</a></li> <li><a href="initialquiz.php">Initial Quiz</a></li> <li><a href="about.php">About</a></li> </ul> </div> </div> </div> <div class="clearbottom"></div> <div id="footer"> <p id="legal"> </p> </div> </div> </div> </body> </html> Hello php gurus,...i need some help here for my php online quiz application. I am doing an online quiz application,where at first a tutor will enter the question and selection of answers,and following by the correct answer through a form. Code: [Select] <html> <body> <form action="insert.php" method="post"> <p>Question: <input type="text" name="Q" /> </p ><p>Answer1: <input type="text" name="A" /> </p> <p>Answer2: <input type="text" name="B" /> </p> <p>Correct Answer: <input type="text" name="ans" /> </p> <p> <input type="submit" /> </p> </form> </body> </html> All the details will be sent to mysql database,and the database structure will be like this : Quote Question AnswerA AnswerB CorrectAnswer 1+1 2 4 A 2+3 6 5 B After that,i have created a php codes to retrieve the Questions from database,and display it in webpage,and the AnswerA and AnswerB will be shown in radio button.So users can choose the answer using radio button... My problem is,i don't know how to compare the 'value' in radio button with the 'CorrectAnswer' in the database,to know the correct answer. And also don't have idea how to calculate the correct answer and getting the results. So,if anyone could help me..i will be really gratefull... Hope can get the solution....plss help me Thank you very much I have attached my documents here... [attachment deleted by admin] I am creating a quiz, with Multiple choice, true and false, and fill in the blanks questions.
The first 2 types are working fine, and I am working on tesing the fill the blank questions...
See code:
//QUESTION 9 if (empty($_POST["ix"])) { $ixErr = "Please select an answer."; } else { $ix = test_input($_POST["ix"]); // check if question only contains letters and whitespace if (!preg_match("/^[a-zA-Z ]*$/",$ix)) { $ixErr = "Only letters and white space allowed."; else ($ix == "charming") { $score = $score+10; echo "<p>9.) " . $ix . " is correct.</p>\n"; } else { echo "<p>9.) " . $ix . " is incorrect.</p>\n"; } } }First, I am testing to see if it is empty, if yes, display error, otherwise use the test_input function on the entered information. Then I want to test and verify that the entered data only contains characters and/or blank spaces, if that returns yes, then I want to test the content for the correct answer. But for some reason the code gets stuck upon testing for the correct answer, please note: I did try elseif, but same issue, please help, thank you. Hi, My name is Karel van der Veen. I am trying to creat a script for a quiz on my website but I am stuck. I was hoping you might have an idea for the solution. The idea is a page with a picture and multiple choice questions about that picture. For example a picture of a bike. Question 1: what colour is the bike? --> choices are green, red, blue. Question 2: what shape are the wheels? --> round, square. I have made a script that compares the answers given by the student, with the correct answers I put in the database corresponding with the bike on the picture. If the student has it right, than after clicking on "next", the "correct answer" page will load. If he made a mistake a "wrong answer" page will load. So far the script works. But what I would like to happen is if the student gives a wrong answer, that after clicking on the `next` button, he will go back to the front page where the picture and the questions are with a sign or mark around the question he answered wrong, so he knows what question he had wrong and has to answer again. Below is the script I have so far. Do you know what I have to change or to add to the script? regards Karel Code: [Select] script of the question page: <?php $array_vorm = Array("rond","vierkant"); $array_kleur= array("rood","blauw","groen"); $array_grootte = array("4x4","8x8"); ?> <form method="post" action="results.php"><br /> <div id="vorm"> <div id="vorm1"><img src="images/vorm.gif" alt="vorm" width="75" height="75" class="vorms" /></div> <div id="vorm2"> <table> <tr><td> <label class="vormhead">VORM</label><br> <select name="form_vorm[]" class="randmenu" size="4" multiple > <option><?php echo implode("</option><option>",$array_vorm); ?></option> </select> </td></tr> </table> </div> </div> <div id="kleur"> <div id="kleur1"><img src="images/kleur.gif" alt="vorm" width="75" height="75" class="kleur" /></div> <div id="kleur2"> <table> <tr><td> <label class="kleurhead">KLEUR</label><br> <select name="form_kleur[]" class="randmenu" size="4" multiple > <option><?php echo implode("</option><option>",$array_kleur); ?></option> </select> </td></tr> </table> </div> </div> <div id="grootte"> <div id=" grootte 1"><img src="images/ grootte .gif" alt="vorm" width="75" height="75" class=" grootte " /></div> <div id=" grootte2"> <table> <tr><td> <label class=" grootte head">GROOTTE</label><br> <select name="form_ grootte []" class="randmenu" size="4" multiple > <option><?php echo implode("</option><option>",$array_ grootte ); ?></option> </select> </td></tr> </table> </div> </div> <input type="submit" class="zoekbalk" value="zoeken" /> And this is the script of the result page: <?php error_reporting ( E_ALL | E_STRICT ); ini_set ( 'display_errors', 1 ); ?> <?php include 'connect.php'; ?> <?php $geenbeschrijving = "De beschrijving is onjuist. $geenselectie = "Je hebt geen selectie gemaakt, maak eerst een selectie en klik dan op zoeken. <br/><br/> $antwoord = "Antwoord: "; $diagnose = "Beschrijving: "; $diagnose2 = "Diagnose: "; $vormeggo = "Vorm: "; $kleureggo = "Kleur: "; $grootteeggo = "Grootte: "; $array_vorm = array("rond","vierkant"); $array_kleur= array("rood","blauw","groen"); $array_grootte = array("4x4","8x8"); if($_SERVER['REQUEST_METHOD'] == 'POST' ) { $query = "select * from foto1 where "; $query_init = $query; $first_option = true; if (isset($_POST["form_vorm"])){ if ($first_option == false){ $query .= " AND "; } else{ $first_option = false; } $query .= "("; for ($i=0; $i<=count($_POST["form_vorm"])-1; $i++){ if ($i == 0){ $query .= "(vorm LIKE '%".$_POST["form_vorm"][$i]."%') "; }else{ $query .= " OR (vorm LIKE '%".$_POST["form_vorm"][$i]."%') "; } } $query .= ")"; } if (isset($_POST["form_ kleur "])){ if ($first_option == false){ $query .= " AND "; } else{ $first_option = false; } $query .= "("; for ($i=0; $i<=count($_POST["form_ kleur "])-1; $i++){ if ($i == 0){ $query .= "( kleur LIKE '%".$_POST["form_ kleur "][$i]."%') "; }else{ $query .= " AND (kleur LIKE '%".$_POST["form_ kleur "][$i]."%') "; } } $query .= ")"; } if (isset($_POST["form_ grootte "])){ if ($first_option == false){ $query .= " AND "; } else{ $first_option = false; } $query .= "("; for ($i=0; $i<=count($_POST["form_ grootte "])-1; $i++){ if ($i == 0){ $query .= "( grootte LIKE '%".$_POST["form_ grootte "][$i]."%') "; }else{ $query .= " AND (grootte LIKE '%".$_POST["form_ grootte "][$i]."%') "; } } $query .= ")"; } if ($query == $query_init){ echo "<div class=\"geenbeschrijving\">" . $geenselectie . "</div>"; }else{ //echo $query."<br><br>"; if ($result = mysql_query($query)) { if (mysql_num_rows($result)<>0) { while ( $row = mysql_fetch_assoc ( $result ) ) { echo "<div class=\"beschrijving\">" . $antwoord . "</div>"; echo "<div class=\"keuze\">" . $vormeggo . $row["VORM"]. "</div>"; echo "<div class=\"keuze2\">" . $kleureggo . $row["KLEUR"]. "</div>"; echo "<div class=\"keuze2\">" . $grootteeggo . $row["GROOTTE"]. "</div>"; </div>"; $beschrijvingquery = "select BESCHRIJVING from beschrijving where Catalog_ID=".$row["ID"]; if ($beschrijvingresult = mysql_query($beschrijvingquery)) { if (mysql_num_rows($beschrijvingresult)<>0) { while ( $beschrijvingrow = mysql_fetch_assoc ( $beschrijvingresult ) ) { echo "<div class=\"beschrijving\">" . $diagnose . "</div>"; echo "<div class=\"beschrijving2\">" . $beschrijvingrow["BESCHRIJVING"]."</div></br>"; } } else { echo "geen beschrijving<br />"; } } $diagnosequery = "select DIAGNOSE from diagnose where Catalog_ID=".$row["ID"]; if ($diagnoseresult = mysql_query($diagnosequery)) { if (mysql_num_rows($diagnoseresult)<>0) { while ( $diagnoserow = mysql_fetch_assoc ( $diagnoseresult ) ) { echo "<div class=\"beschrijving\">" . $diagnose2 . "</div>"; echo "<div class=\"beschrijving2\">".$diagnoserow["DIAGNOSE"]."<br /><br />"; } } else { echo "geen beschrijving<br />"; } } $fotoquery = "select FOTOthumb, FOTObig from foto where Catalog_ID=".$row["ID"]; if ($fotoresult = mysql_query($fotoquery)) { if (mysql_num_rows($fotoresult)<>0) { while ( $fotorow = mysql_fetch_assoc ( $fotoresult ) ) { echo "<div class=\"beschrijving4\">" .'<a title="' . $fotorow['FOTObig'] . '" href="images/big/' . $fotorow['FOTObig'] . '" rel="lightbox"><img src="images/thumb/' . $fotorow['FOTOthumb'] . '"></a></br></br><hr><hr> '; } } else { echo "<img src='geenfoto.jpg' alt='geen foto' /><br />"; } } } } else { echo "<div class=\"geenhuidaandoeningen\">" . $geenhuidaandoeningen . "</div>"; } } } } ?> |