I am trying to make a quiz using PHP and Mysql. I have create my database and filled it. The database is construct as follows: question_id(P.K),question, right answer, annswer1,answer2, answer3,level and test_id(F.K).
I have created a query that "draws" questions in a random order and I have shuffled the answers. The PHP script for showing the Qs and As to the user is the following:
while ($index <= (count($test)-1)){
echo $test[$index]['question']. "<br/>";
$question_id=$test[$index]['question_id'];
$s_ans=User_Model::shuffle_answers($question_id);
foreach ($s_ans as $s_a){
echo "<input type='radio' name='test_ans[$index][$s_a]' id='$question_id' />$s_a <br />";
}
echo "<hr/>";
$index++;
}
The above code shows all questions and their answers at once.
What I would like to do, and couldn't successfully get it done, is to show each question separately and when the user presses the "next" button, the next question accompanied by its answers will be shown to him.
So,
a)is there a way I can achieve that?
b)when I try to access user's answers I get the following output:
Array ( [0] => Array ( [I like ice cream => on ) [1] => Array ( [i don't go to school] => on ) [2] => Array ( [i play basketball] => on ) [3] => Array ( [i like sailing] => on ) )
How can i access the user's answers as to compare them with the right answer?
Well, since you're using PHP you can use sessions or cookies. It's probably not the most elegant solution, but I'd generate a reference string that represents a sequence of questions and store it in one session or cookie variable, and then have another session or cookie variable that represents the current position in the quiz. Furthermore you could have additional variables to keep track of score and other tidbits. Then when they hit the next button you just update variables and display the next question, or the end of the quiz if you've reached it.
If you want to do it dynamically without having to load another page then you'll need to look into javascript.
Multipage quizzes are very easy to do.
A) This can be done by removing the while() loop, but leave the counter to pass through a hidden <input> OR increasing the $_SESSION variable
$index = $_POST['index'] // OR $_GET['index'] OR $_SESSION['index'] depending on your form method
echo $test[$index]['question']. "<br/>";
$question_id=$test[$index]['question_id'];
$s_ans=User_Model::shuffle_answers($question_id);
foreach ($s_ans as $s_a){
echo "<input type='radio' name='test_ans[$index][$s_a]' id='$question_id' />$s_a <br />";
}
if ($index < $total_questions){
$index++; // Increase var, and then use in hidden input
echo "<input type='hidden' name='index' value='$index' />";
echo "<input type='submit' name='submit_answer' value='Next' />";}
else {
echo "<input type='submit' name='submit_answer' value='You Are Done' />";}
//OR
$_SESSION['index'] = $index++;
B) Without your code, this is just an example -
if ($user[$index]['their answer'] == $test[$index]['right answer'])
{ echo "You were correct";}
else
{ echo "Sorry, your answer was incorrect";}
Related
I've created a php page which retrieves question and options(as MCQ's) from the database and in that Radio buttons are created dynamically using echo()The name for each radio button group is assigned into an array from which one by one index's value is set to the name attribute.Example:
$result=mysqli_query($db,$sql);
$numrows=mysqli_num_rows($result);//gets the number of questions
$radiogrp_name=array();
for($i=0;$i<$numrows;$i++){ //creating array of names for each set of radio buttons
$radiogrp_name[$i]="q".$i;
}
$i=0;
while(($myrow=mysqli_fetch_array($result)) && ($i<$numrows)){
echo $myrow["q_no"].". ";
echo $myrow["ques"]."<br><br>";
echo "<input type='radio' name='$radiogrp_name[$i]' value='a'/>".$myrow["A"]."<br>";
echo "<input type='radio' name='$radiogrp_name[$i]' value='b'/>".$myrow["B"]."<br>";
echo "<input type='radio' name='$radiogrp_name[$i]' value='c'/>".$myrow["C"]."<br>";
echo "<input type='radio' name='$radiogrp_name[$i]' value='d'/>".$myrow["D"]."<br><br><br>";
$i++;
}
How would I get the selected radio buttons and set them into a SESSION variable? Can anyone help with this? Or any other way to implement this?Thank you in advance!
On the page that the form is POST'ed to you are going to need to look through the $_POST array and strip out the relevant answers. Ideally you would have a list of expected indexes to drive that page, but if not you could just try to pattern match the indexes.
Something like:
$results = array();
foreach($_POST as $key => $value){
if(preg_match("/q(\d{1,3})/", $key, $matches)){
$results[$matches[1]] = $value;
}
}
results would then contain an array of values indexed by the numeral in name="q#" and you would just set it to the session or do with it whatever you need.
EDIT
by the way, you'll need to wrap your string inclusion in curlies since it is an array.
echo "<input type='radio' name='{$radiogrp_name[$i]}' value='d'/>"
I know for a fact option 1 is right as it works for me.
OPTION 1
echo "<input type='text' name='text1' id='text1' value='".$_SESSION['txt']."'>";
But in a situation where text boxes are a result of an array, if I change the above to the following is it correct? I know the name='text1[]' bit is right however can some one tell me how do I change the value attribute in the option 2?
OPTION 2
echo "<input type='text' name='text1[]' id='text1' value='".$_SESSION['txt[]']."'>";
you can put the array in to session :-
$my_array=array('ct', 'dg', 'se', 'ir');
// put the array in a session variable
$_SESSION['code']=$my_array;
foreach($_SESSION['code'] as $key=>$value)
{
// and print out the values
echo "<input type='text' name='text1[]' id='text1' value='".$_SESSION[$key]."'>";
}
I'm working on this code in PHP and basically I have 5 checkboxes, for 5 individual items, each called "ItemCheck" and they have values of 0-4. Now I wrote a code where it has it so it displays the numbers that are checked from those 5 check lists.
Form:
for ($i=0;$i<count(5);$i++){
echo "
<input type='checkbox' name='ItemCheck' value='$i.check'>$i</input><br>"}
PHP Process:
if (isset($_POST['ItemCheck'])){
for ($o=0;$o<$ItemCount;$o++){
if($_POST['ItemCheck'] == $o.'.check') {
echo "Item " . $o . "<br>";
}
}
}
else{ echo "You must select at least one product";}
Although say if I check box #1,2 & 3, the final output will only display "Item 3". Now matter how many checkboxes you select, it will only display the one with the highest value and none other. Does anybody know what's wrong with the code and how to have it so it displays each individual number that's selected, and not just the one with the highest value?
What you want to do is set the name of the checkbox element ItemCheck[] this will make $_POST["ItemCheck"] an array.
Example:
for ($i=0;$i<count(5);$i++){
echo "<input type='checkbox' name='ItemCheck[]' value='$i.check'/> $i<br>";
}
Another thing to note is the browser won't post up anything for an unchecked checkbox so I think your processor needs to be like this.
<?php
if (isset($_POST['ItemCheck'])){
for ($o=0;$o<count($_POST['ItemCheck']);$o++){
echo "Item " . $_POST['ItemCheck'] . "<br>";
}
} else {
echo "You must select at least one product";
}
?>
Another thing so make sure of is that your form has the method set to POST
I'm new to php and I was wondering how I would be able to create something like a delete button for deleting items in a list that would be generated from a dynamically growing array.
An example of what I mean is this:
<?php
if (isset($_REQUEST['foo']))
{
if (isset($_SESSION['words']))
{
$_SESSION['words'][] = 'added word';
}
else
{
$_SESSION['words'] = array('cat', 'dog', 'you', 'me');
}
foreach ($_SESSION['words'] as $key => &$value)
{
echo "<p>" .
$value .
" - <input type='submit' name='delete_" .
$value .
"' value='Delete Entry' /></p>";
}
if (isset($_REQUEST['clear']))
{
session_destroy();
}
?>
Where, on every button click that gets sent to my script it would echo out the array with the buttons.
I'd like to link the delete buttons to a function that looked something like:
function delete_entry( $index )
{
unset($_SESSION['words'][$index]);
$_SESSION['words'] = array_values($_SESSION['words']);
}
Is what I'm asking even possible?
Your array of words seem to be stored in your session variable, so I'm assuming that you want to remove/add words to it. How about this...?
Have a separate form for each word with a hidden field saying what the word is:
So in the for loop:
echo "<form><p>".$value." - <input type='submit' value='Delete Entry' /></p><input type=\"hidden\" name=\"delword\" value=\"".$value."\"/></form>";
if(isset[$_REQUEST['delword']]) remove it from the session array (do this before you do your echoing for loop. (You could use array_search to find the element, then run unset as you suggested)
Let me know if you want me to elaborate on this suggestion.
I have a form where im asking for name, surname, phone cellphone and at the end user has to check one or more options in a checkbox and then clicks submit.
After that in the "thank you page" i want to show the exact form but this time to show only the non-checked checkboxes.
Reason for this is that i want to say "We highly recommend you check all the options for better results, you can do so by simply clicking the submit button below"
And then below that i want to present the form as i said, but the remaining checkboxes (the oens that were not checked before) would be only the NON-checked options in the previous page. Makes sense?
Ive tried hard with php if states and switches but still cant get the result i want, it seems i have to define "false statements" in a way im not cabable of doing it.
Should i use php or jquery?
Can anyone help me? Im kinda lost.
Thanks a lot in advance
(EDIT: Post-reworded after question edited)
Ok, my suggested solution is still similar to the one before you reworded the question. You have a list of checkboxes? I'd start by putting the names of these checkboxes in to an array:
$checkboxes = Array("checkbox1" => 0, "checkbox2" => 0, "checkbox3" => 0);
Render your list of checkboxes using this array for consistency (this prevents you adding a checkbox not in the list, etceteras). Render only those whose value is '0'.
When you submit your form and are processing the $_POST, you can set to '1' any checkbox that has been ticked. Re-render the checkboxes (it will only do those with a value of 0)
EDIT: Sorry it took so long, am a bit busy and my php is kind of rusty. I apologise to every PHP programmer that reads this, it is quick and dirty!!"
<?php
function renderCheckboxes($checkBoxes)
{
foreach($checkBoxes as $field => $value)
{
if($value == 0)
echo("<input type=\"checkbox\" name=\"$field\" />".
"<label for\"=$value\">$field</label><br/>");
}
}
// initialise possibibilites
$array = Array("Name" => 0,
"Tel" => 0,
"Address1" => 0,
"Address2" => 0,
"Town" => 0,
"Postcode" => 0,
"Country" => 0);
// process form here
$posting = count($_POST) > 0;
if($posting) // submitting?
{
foreach($_POST as $field => $value)
$array[$field] = 1;
}
echo("<html>".
"<body>".
"<form name=\"frmTest\" id=\"frmTest\" method=\"post\" action=\"test.php\">");
if($posting)
echo("We highly recommend you select the following:<br/>");
renderCheckboxes($array);
echo("<input type=\"submit\" value=\"Submit\" />".
"</form>".
"</body>".
"</html>");
?>