PHP - Form Checking During Quiz
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> Similar TutorialsI have created a form where the user enters their first name, last name, work hours, and rate. I want to add a check so that once submit is pressed, the page will return an error if one of the fields was left blank. How can I do it?? I have been trying for hours... Here is my code: <html> <title> Pay Calculator </title> <form method='post' action='pay2.php'> First Name: <input type='text' name='first' value="<?php echo ($_POST['first']); ?>" <br/> Last Name: <input type='text' name='last' value="<?php echo ($_POST['last']); ?>" <br/> Hours of Work: <input type='text' name='hours' value="<?php echo ($_POST['hours']); ?>" <br/> Hourly Pay Rate: <input type='text' name='rate' value="<?php echo ($_POST['rate']); ?>" <br/> <input type='submit' value='submit'> </form> </html> <?php $pay = $_POST['pay']; $hours = $_POST['hours']; $extra = $_POST['extra']; $rate = $_POST['rate']; if ($hours > 40){ $extra=$hours-40; $hours=40; $pay=($extra*1.5*$rate)+($hours*$rate); } else { $pay=$hours*$rate; } if (empty($_POST['$first'])) {print "**Please enter your first name\n";} echo "\n Your pay is: <br /> $ $pay <br />" ; ?> The below is flagging errors #3 and #9. Error #3 is being thrown even though the emails match. Code: [Select] <?php session_start(); $_SESSION['submitted']="yes"; $error=$_GET['error']; $date_rma="5/10/2011"; $content=' <div class="content_text"> <div class="content_header">Request RMA Number</div> <p>Enter the information you used on PayPal, that you completed your order with. The information must match, or a RMA Number will not be issued.</p> <form action="./rma_process.php" method="post"> <p><label>Name:</label> <input type="text" name="name" size="30" value="'.(isset($_SESSION['name']) ? $_SESSION['name'] : '').'" />'; if($error[0]==1){ $content.=' <span class="red bold">This field is required.</span>'; } $content.='</p> <p><label>E-Mail Address:</label> <input type="email" name="email" size="35" value="'.(isset($_SESSION['email']) ? $_SESSION['email'] : '').'" />'; if($error[1]==1){ $content.=' <span class="red bold">This field is required.</span>'; } $content.='</p> <p><label>Confirm E-Mail Address:</label> <input type="email" name="confirm_email" size="35" value="'.(isset($_SESSION['confirm_email']) ? $_SESSION['confirm_email'] : '').'" />'; if($error[2]==1){ $content.=' <span class="red bold">This field is required.</span>'; } if($error[3]==1){ $content.=' <span class="red bold">E-Mail addresses do not match.</span>'; } $content.='</p> <p><label>Phone Number:</label> <input type="text" name="phone" size="15" value="'.(isset($_SESSION['phone']) ? $_SESSION['phone'] : '').'" /> Ext. <input type="text" name="ext" size="4" value="'.(isset($_SESSION['ext']) ? $_SESSION['ext'] : '').'" />'; if($error[4]==1){ $content.=' <span class="red bold">A properly formatted phone number is required.</span>'; } $content.='</p> <p><label>Date of Purchase (MM/DD/YYYY):</label><input type="text" name="month" size="2" maxlength="2" value="'.(isset($_SESSION['month']) ? $_SESSION['month'] : '').'" /> <input type="text" name="day" size="2" maxlength="2" value="'.(isset($_SESSION['day']) ? $_SESSION['day'] : '').'" /> <input type="text" name="year" size="5" maxlength="4" value="'.(isset($_SESSION['year']) ? $_SESSION['year'] : '').'" />'; if($error[5]==1 || $error[6]==1 || $error[7]==1){ $content.=' <span class="red bold">A properly formatted date is required.</span>'; } $content.='</p><p><label>List the Products you wish to return. Sperate with a comma. <br />Use either the whole product name, or the GHP# Product Code:</label>'; if($error[8]==1){ $content.=' <span class="red bold">This field is required.</span>'; } $content.='<textarea name="products_returning" rows="10" cols="60"> '.(isset($_SESSION['products_returning']) ? $_SESSION['products_returning'] : '').''; $content.=' </textarea> <input type="hidden" name="submitted" value="yes" /> </p> <p><input type="submit" value="Submit" name="Submit" /></p> </form> </div> '; ?> Code: [Select] <?php session_start(); $name = $_POST['name']; $_SESSION['name']=$name; if($name==""){ $error0=1; } else{ $error0=0; } $email = $_POST['email']; $_SESSION['email']=$email; if($email==""){ $error1=1; } else{ $error1=0; } $confirm_email = $_POST['confirm_email']; $_SESSION['confirm_email']=$confirm_email; if($confirm_email==""){ $error2=1; } else{ $error2=0; } if($email!=$confirm_email){ $error3=1; } else{ $error3=0; } $phone = $_POST['phone']; $_SESSION['phone']=$phone; if($phone==""){ $error4=1; } else{ $error4=0; } $ext = $_POST['ext']; $_SESSION['ext']=$ext; $phone = $phone.' Ext.'.$ext; $month = $_POST['month']; $_SESSION['month']=$month; if($month=="" || !is_numeric($month)){ $error5=1; } else{ $error5=0; } $day = $_POST['day']; $_SESSION['day']=$day; if($day=="" || !is_numeric($day)){ $error6=1; } else{ $error6=0; } $year = $_POST['year']; $_SESSION['year']=$year; if($year=="" || !is_numeric($year)){ $error7=1; } else{ $error7=0; } $date="".$month."/".$day."/".$year.""; $products_returning = $_POST['products_returning']; $_SESSION['products_returning']=$products_returning; if($products_returning==""){ $error8=1; } else{ $error8=0; } if($_SESSION['submitted']=="yes"){ $error9=0; } else{ $error9=1; } $error="".$error0."".$error1."".$error2."".$error3."".$error4."".$error5."".$error6."".$error7."".$error8."".$error9.""; if($error!=="0000000000"){ header("Location: ./index.php?returns=rma&error=".$error0."".$error1."".$error2."".$error3."".$error4."".$error5."".$error6."".$error7."".$error8."".$error9.""); } else{ header("Location: ./index.php?returns=submitted"); } ?> Following is the form.Now i want to see if submit button is pressed or not.Usually if html had Code: [Select] <input type="submit" value="Submit" name = "submit" /> i would simply use Code: [Select] <?php if(isset($_POST['submit'])) ?> But below is the form which has an image as a submit button Form - Code: [Select] <form action="" method="post" id="sendemail"> <ol> <li> <label for="name">Name (required)</label> <input id="name" name="name" class="text" /> </li> <li> <label for="email">Email Address (required)</label> <input id="email" name="email" class="text" /> </li> <li> <label for="email">Phone number</label> <input id="phone" name="phone" class="text" /> </li> <li> <label for="address">Address(required)</label> <input id="address" name="address" class="text" /> </li> <li> <label for="city">City(required)</label> <input id="city" name="city" class="text" /> </li> <li> <label for="state">State(required)</label> <input id="state" name="state" class="text"/> </li> <li> <label for="zipcode">Pincode/Zipcode(required)</label> <input id="zipcode" name="zipcode" class="text" /> </li> <li> <input type="image" name="submit" id="imageField" src="images/submit.gif" class="send" /> <div class="clr"></div> </li> </ol> </form> How should i check if form is submitted or not when instead of submit button there is an image ? ----------------------------------------------------------------- Alternative Solution ---------------------------------------------------------------------------- I tried sending it to other page but then i had to send an array back to this page and i didn't know how to send that either.I tried Code: [Select] <?php $error = serialize($error); echo "<meta http-equiv='refresh' content='0;url=about.php?array=".$error."'> "; ?> But even after Code: [Select] $array = unserialize($array); $array contained nothing. Can someone please show me how to send in array in between pages for future ? I read ages ago (and checked to see if it's true, it was and given how it works, it must still be) the end user can alter the value of any form field, using Firebug or similar, before submitting it. Two things I've figured out today: 1) a form input doesn't need a value - doesn't even need the attribute - if you're only checking whether the POST var isset and the actual value isn't important 2) Although it appears not to matter in the example I'm working on now, if the script doesn't check what the value is, and potentially sanitise it, the user could submit the form with any value, true, false, malicious, idk... So my question is: is this one of the ways malicious bad things can happen and do I *have to* specify a value, not because the script won't work without it, it does, but because in the real world it opens a security door if I don't check for malicious script by saying "if value not as expected, script has to die". Having formulated the question properly and thought about it I can't imagine simply making a form, without obvious connections to anything important, could be a problem in the way I'm asking about but I asked it now so Edited by appobs, 03 July 2014 - 12:08 PM. I've decided to rewrite one a couple of my forms, to make them more user friendly. But I am having problems returning the error. I've created an array ($e) which has the field name ($e['field_name']) for the error, but it isn't displaying any errors. Here's the code: case "contact": $e = array(); if(isset($_POST['sb'])){ $fullname = $sql->real_escape_string($_POST['fullname']); $email_a = $sql->real_escape_string($_POST['email']); $email_r = $sql->real_escape_string($_POST['email_r']); $orderid = $sql->real_escape_string($_POST['orderid']); $subject = $sql->real_escape_string($_POST['subject']); $problem = $sql->real_escape_string($_POST['problem']); # Error Message function show_error($error,$evar){ $err = ' <span style="color: #ff0000"><strong>'.$error.'</strong></span>'; return $err; } # Check for isset if(!isset($_POST['fullname'])){ $e['fullname'] = show_error('Please enter your full name',$e['fullname']); } if(!isset($_POST['email_a'])){ $e['email_a'] = show_error('Please enter your email address.',$e['email_a']); } if(!isset($_POST['email_r'])){ $e['email_r'] = show_error('Please re-enter your email address.',$e['email_r']); } if(!isset($_POST['subject'])){ $e['subject'] = show_error('Select a subject.',$e['subject']); } if(!isset($_POST['problem'])){ $e['problem'] = show_error('Describe your problem.',$e['problem']); } if(isset($_POST['email']) AND isset($_POST['email_r']) AND $email_a != $email_r){ $e['email_r'] = show_error('Your email addresses do not match.',$e['email_r']); } } $content = '<h2> Customer Support - Contact</h2> <p> For technical support, sales and product related questions: <a href="'.$tech_support.'" target="_blank">Technical Support</a>.</p> <p> For downloading, ordering, refund or other store related questions, please fill out the form below:</p> <form method="post" name="csupport"> <p> Please enter your full name:<br /> <input name="fullname" type="text" value="'.$fullname.'" />'.$e['fullname'].'</p> <p> Please enter your email address:<br /> <input name="email_a" type="text" value="'.$email_a.'" />'.$e['email_a'].'<br /> Please re-enter your email address:<br /> <input name="email_r" type="text" value="'.$email_r.'" />'.$e['email_r'].'</p> <p> Please enter your order number:<br /> <input name="orderid" type="text" value="'.$orderid.'" /></p> <p> Please select a subject for your enquiry:<br /> <select name="subject"><option selected="selected" value="">--Select--</option><option value="Billing Question">Billing Question</option><option value="Cancel / Refund Order">Cancel / Refund Order</option><option value="Download Question">Download Question</option><option value="Password Issues">Password Issues</option><option value="Order Question">Order Question</option><option value="Shipping Question">Shipping Question</option><option value="Other">Other</option></select>'.$e['subject'].'</p> <p> Describe your problem as best you can:<br /> <textarea cols="45" name="problem" rows="4">'.$problem.'</textarea>'.$e['problem'].'</p> <p> <input name="sb" type="hidden" value="sb" /><input name="submit" type="submit" value="Submit" /></p> </form> '; $title = 'Contact Support'; break; Can anyone see what the problem is? Thanks 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
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.... 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!!! " 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; ?> 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 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. 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.'; } ?> 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 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 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>"); } ?> |