Setting up a quiz in php that accepts slightly wrong answers - php

So recently I was looking into PHP and I have managed to set up a little quiz making use of it. The question that I have is how would I make the quiz accept slightly spelt wrong answers? For example if my quiz asked what was the capital of Alabama and someone spelt Montgomery slightly wrong how would I allow it to still count it as right? I would like to do this for all of the questions that my quiz ask and I hope I have worded my question well enough, if not let me know. Here is the code I am currently using, and yes it is set up into three files as I find having it in one file complicated and I please would like answers referring to the multiple files I have, I would not like an example of all of the php code on one page if possible. Code:
Code for listing the states and capitals, not full list but example:
<?php
$states = Array();
$capitals = Array();
$states[]="Alabama";
$capitals[]="Montgomery";
$states[]="Alaska";
$capitals[]="Juneau";
$states[]="Arizona";
$capitals[]="Phoenix";
$states[]="Arkansas";
$capitals[]="Little Rock";
$states[]="California";
$capitals[]="Sacramento";
$states[]="Colorado";
$capitals[]="Denver";
$states[]="Connecticut";
$capitals[]="Hartford";
$states[]="Delaware";
....etc
?>
The actual main code for the base of the quiz:
<!DOCTYPE html>
<html>
<head>
<title>State capital quiz: ask</title>
</head>
<body>
<h1>State Capital Quiz </h1><p>
<?php
$saywhich=#$_GET['saywhich'];
if ($saywhich){
include("statecapitals.php");
$which=$_GET['which'];
$choice=rand(0, sizeOf($states)-1);
if ($which=='state') {
$state = $states[$choice];
print("What is the capital of $state?<br>");
print("<form action='statecapquizcheck.php' method='get'>\n");
print("<input type='text' name='capital'><br>\n");
print("<input type='hidden' name='which' value=$which>\n");
print("<input type='hidden' name='choice' value=$choice>\n");
print("<input type='submit' value='Submit Answer'>");
print("</form>\n");
}
else {
$capital = $capitals[$choice];
print("$capital is the capital of which state?<br>");
print("<form action='statecapquizcheck.php' method='get'>\n");
print("<input type='text' name='state'><br>\n");
print("<input type='hidden' name='which' value=$which>\n");
print("<input type='hidden' name='choice' value=$choice>\n");
print("<input type='submit' value='Submit Answer'>");
print("</form>\n");
}
}
else {
print("Choose form of question: do you want to be given the state or the capital?<br>");
print("<form action='statecapquizask.php' method='get'>\n");
print("Ask <input type='radio' name='which' value='state'>State");
print(" <input type='radio' name='which' value='capital'>Capital\n");
print("<input type='hidden' name='saywhich' value='true'>\n");
print("<input type='submit' value='Submit choice'>");
print("</form>");
}
?>
</body>
</html>
Code for checking if the answers are correct:
!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>State capitals quiz: check</title>
</head>
<body>
<h1>State Capital Quiz </h1><p>
<?php
include('statecapitals.php');
$choice=$_GET['choice'];
$state=#$_GET['state'];
$capital=#$_GET['capital'];
$which=$_GET['which'];
$correctstate=$states[$choice];
$correctcapital=$capitals[$choice];
if ($which=='state') {
if ($capital == $correctcapital) {
print("Correct! $correctcapital is the capital of $correctstate!");
print("<p><a href='statecapquizask.php'>Play again </a>");
}
else {
print("WRONG!<p>\n");
print("<a href='statecapquizask.php'>New turn </a><p>\n");
print("OR try again: What is the capital of $correctstate?<br>");
print("<form action='statecapquizcheck.php' method='get'>\n");
print("<input type='text' name='capital'><br>\n");
print("<input type='hidden' name='state' value=$state>\n");
print("<input type='hidden' name='which' value=$which>\n");
print("<input type='hidden' name='choice' value=$choice>\n");
print("<input type='submit' value='Submit Answer'>");
print("</form>\n");
} }
else {
if ($state == $correctstate) {
print("Correct! The capital of $correctstate is $correctcapital!");
$saywhich='false';
print("<p><a href='statecapquizask.php'>Play again </a>");
}
else {
print("WRONG!<p>\n");
print("<a href='statecapquizask.php'>New turn </a><p>\n");
print("OR try again: $correctcapital is the capital of what state?<br>");
print("<form action='statecapquizcheck.php' method='get'>\n");
print("<input type='text' name='state'><br>\n");
print("<input type='hidden' name='capital' value=$capital>\n");
print("<input type='hidden' name='which' value=$which>\n");
print("<input type='hidden' name='choice' value=$choice>\n");
print("<input type='submit' value='Submit Answer'>");
print("</form>\n");
} }
?>
</body>
</html>

I hope you've had enough time to play around with this on your own, because that's how you learn.
If you've taken the time to hack this on your own, then I submit this script for anything you might glean from it. I took your scenario and wrote a procedural script to try it out; I was curious about soundex(). Yes, this is a one-pager... Not at all the way I would normally do things, as I would use classes so that it is unit testable.
This uses the convention of PHP on the top; HTML on the bottom. This helps enforce separation of logic and presentation.
The html might or might not work; it is untested.
FWIW, I discovered that soundex is very, very, very forgiving! So instead, I used metaphone.
<?php
// initialize all variables
$get = $_GET; // this was done for testing and I'm too lazy to replace it ;)
$success = false;
$choose_which = true;
$supplied_term = '';
$which = '';
$checked_answer = false;
$answer_array = array();
// state => capital
$states = array(
'Alabama' => 'Montgomery',
'Alaska' => 'Juneau',
'Arizona' => 'Phoenix',
'Arkansas' => 'Little Rock',
'California' => 'Sacremento',
// ... etc
);
// capital => state
$capitals = array_flip($states);
function get_random($stateOrCapital) {
$indexed_list = array_keys($stateOrCapital);
$random_index = (rand(0, sizeOf($indexed_list)-1));
return $indexed_list[$random_index];
}
function check_answer($submitted,$correct) {
//return (soundex($submitted) == soundex($correct)); // too forgiving
return (metaphone($submitted) == metaphone($correct));
}
// are we checking state or capital? Decouple GET input, choose which list to use for answers
if( array_key_exists('which', $get)) {
// don't show radio buttons
$choose_which = false;
switch($get['which']) {
case 'capital':
$which = 'capital';
$answer_array = $capitals;
break;
default:
$which = 'state';
$answer_array = $states;
}
}
// show question?
if($choose_which == false) {
$supplied_term = get_random($answer_array);
}
// check answer?
if( array_key_exists('check_answer', $get)) {
$supplied_term = htmlentities($get['supplied_term']);
$correct_answer = $answer_array[$supplied_term];
$success = check_answer($get['answer'],$correct_answer);
$checked_answer = true;
}
// default is to ask which type of question
// everything below could be separated into a view.
?><html>
<head>
<title>State capital quiz</title>
</head>
<body>
<h1>State Capital Quiz </h1>
<?php if($checked_answer): ?>
<?php if($success): ?>
<h2>CORRECT</h2>
<?php else: ?>
<h2>Sorry, try again...</h2>
<?php endif; ?>
<?php endif; ?>
<?php if($choose_which || $success): ?>
<h2>Which do you wish to answer?</h2>
<form action='' method="get">
<div><label>Capital <input type='radio' name='which' value='capital' /></label></div>
<div><label>State <input type='radio' name='which' value='state' /></label></div>
<div><input type='submit' /></div>
</form>
<?php else: ?>
<p>What is the matching state or capital for <?= $supplied_term ?></p>
<form action='' method='get'>
<input type='hidden' name='check_answer' value='true'>
<input type='hidden' name='which' value='<?= $which ?>'>
<input type='hidden' name='supplied_term' value='<?= $supplied_term ?>'>
<input type='text' name='answer'><br>
<input type='submit' value='Submit Answer'>
</form>
<?php endif; ?>

Related

How to save checkbox status after form is submitted

I have a PHP code to display table data with a column of checkboxes used to click to mark the test case as Blocked. I am trying to save the state of checkbox after it is submitted, but I am unable to do so.
Please help!
echo "<form id=\"checkbox\" class=\"check2\" method = \"post\" action=\"\">";
$checked = "";
if(isset($_POST['Blocked[]'])) {
$checked = 'checked="checked"';
}
echo "<td $Blocked><input type =\"checkbox\" name=\"Blocked[]\" value=\"checkblock\" onclick=\"showMsg('div1')\" $checked/></td>";
echo "<input type=\"submit\" value=\"Submit\" class=\"button\" name=\"edit_tc\" onclick=\"myFunction(form)\" style=\"position:fixed; height:25px ; width:150px; bottom:25px; right:200px;\"/>";
echo "</form>";
Firstly, please don't echo the static html like above because it makes the code reading difficult. Secondly, you are using the isset() function incorrectly. Thirdly, your input field name for checkbox is of type array. Do you really need this to be an array?
Please use something like this:
<?php
$checked = '';
if(isset($_POST['Blocked'])) {
$checked = 'checked="checked"';
}
?>
<form id="checkbox" class="check2" method = "post" action="">
<input type ="checkbox" name="Blocked" value="checkblock" onclick="showMsg('div1')" <?php echo $checked;?>/>
<input type="submit" value="Submit" class="button" name="edit_tc" onclick="myFunction(form)" style="position:fixed; height:25px ; width:150px; bottom:25px; right:200px;"/>
</form>

how to make drop-down form to remember input in php

im creating a form which will display data from database, everything is set so far, but i want the form to remember the data in case if user has to write it down again in case of error. I found some similar code concerning only html, but when including php to display a form i find some difficulties for code to remember the last input (current problem is only concerning drop down selection list):
$Type = $_POST['petType']; //this should remember last input
<?php
/*upload form and drop-down selection list*/
echo "
<div align='left'>
<form enctype='multipart/form-data' action='ChoosePetCategory.php' method='POST'>
<input type='hidden' name='MAX_FILE_SIZE' value='500000000' />
<input type='file' name='imagePath' size='600' />
<select name='petType'>\n
<option value='-1'>Type:</option>";
while($row = mysqli_fetch_assoc($PetListResult))
{
extract($row);
echo "<option value='$petType' ";
if($Type == '$petType')
{
echo "? selected='selected'";
// i need to make selected true only for last selected option,
//and redisplay it in the same form again
}
echo ">$petType </option>";
}
echo "</select>
<p><input type='submit' name='Upload' value='Add Pet' />
</form>
?>
try this:
<?php
$Type = $_POST['petType']; //this should remember last input
?>
<div align='left'>
<form enctype='multipart/form-data' action='ChoosePetCategory.php' method='POST'>
<input type='hidden' name='MAX_FILE_SIZE' value='500000000' />
<input type='file' name='imagePath' size='600' />
<select name='petType'>
<option value='-1'>Type:</option>
<?php
while($row = mysqli_fetch_assoc($PetListResult))
{
extract($row);
?>
<option value='<?php echo $petType;?>' <?php echo $Type == $petType ? "selected=selected":"";?> ><?php echo $petType;?> </option>
}
</select>
<p><input type='submit' name='Upload' value='Add Pet' />
</form>
sidenote: make html and php different , it makes things easier.
You are comparing $Type to a string not a variable.
Try
if($Type == $petType)

HTML reset button not working properly

I have a basic sum example with some PHP and HTML, inside this PHP page the reset button only resetting first two input field, and it is not resetting the third answer field. I dont know what is the error with this cause i am new to PHP. someone please help me to fix this.
code
<html>
<head>
<title>Title goes here</title>
</head>
<body>
<form action="" method="post">
<label>Enter Num1:</label>
<input type="text" name="num1" id="num1" /><br>
<label>Enter Num2:</label>
<input type="text" name="num2" id="num2" /><br><br>
<input type="radio" name="rad" value="add"/>addition
<input type="radio" name="rad" value="sub"/>sub
<input type="submit" name="btn_submit" value="fire">
<?php
if(isset($_POST['btn_submit']))
{
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$rad_val = $_POST['rad'];
if($rad_val=="add"){
$total = $num1+$num2;
}
else if($rad_val=="sub"){
$total = $num1-$num2;
}
echo "<SCRIPT TYPE=\"text/javascript\">
document.getElementById(\"num1\").value= $num1;
document.getElementById(\"num2\").value= $num2;
</SCRIPT>";
echo "<label>Answer is:</label> <input type=\"text\" name=\"rad\" value = $total />";
echo"<input type=\"reset\" name=\"reset\" value=\"reset\" />";
}
else if(isset($_POST['reset'])){
echo "<script>window.location = 'your_page.php';</script>";
}
?>
</form>
</body>
</html>
The reset function loads the your_page.php. So the initial value on that page might be needed to be changed to 0. Could you give an example of your_page.php?
You can trigger a page refresh by changing the line
echo"<input type=\"reset\" name=\"reset\" value=\"reset\" />";
to
echo"<input type=\"reset\" name=\"reset\" value=\"reset\" onclick= \"window.location = 'your_page.php';\"/>";
OR
Even better. Just Reset the value in the Answer to 0, This will save on the page reload.
Add an ID to the result field :
<input type=\"text\" name=\"rad\" id=\"rad\" value = $total />";
And change te value on the reset click/
echo"<input type=\"reset\" name=\"reset\" value=\"reset\" onclick= \" document.getElementById(\"rad\").value= 0;\"/>";
With Jquery you can reset to any value but you net to prevent the default action:
Example:
$('#Reset').click(function(){
event.preventDefault();
$('#element').val('default');
$('#element2').val('default');
$('#element3').val('default');
});

increase by one a variable every time you push a button (PHP)

I'd like that the variable $order is increase by 1 every time I push the submit button.
(The name of the page is study.php so every time I push the button the page is refreshed):
<?php
$order = $_GET['number'];
echo "<form action='study.php' method='GET'>
<input type='hidden' name='number' value='$order++' />
<input class='big_b' type='submit' value='next' />
</form>";
echo "$order";
?>
The first time 1 push the button $order is 1, the second 2, the third is 3 ... etc
Thanks for your help!
EDIT: SOLVED
<?php
session_start();
if(empty($_SESSION['count'])) $_SESSION['count'] = 0;
$order = $_SESSION['count']+1;
$_SESSION['count'] = $order;
echo "<form action='study.php' method='GET'>
<input class='big_b' type='submit' value='next' />
</form>";
echo "$order";
?>
How you currently have it, is that it will increment on each page refresh regardless whether button was clicked or not, do you need it only to increment if the button is pressed?
<?php
session_start();
// Reset to 1
if(isset($_POST['reset'])){unset($_SESSION['number']);}
// Set or increment session number only if button is clicked.
if(empty($_SESSION['number'])){
$_SESSION['number']=1;
}elseif(isset($_POST['next'])){
$_SESSION['number']++;
}
echo '
<form action="" method="POST">
<input class="big_b" type="submit" name="next" value="Next" />
<input type="submit" name="reset" value="Reset" />
</form>';
echo $_SESSION['number'];
?>
<?php
session_start();
if(empty($_SESSION['order'])){
$_SESSION['order'] = 1;
}
echo "<form action='study.php' method='GET'>
<input type='hidden' name='number' value='".$_SESSION['order']++."' />
<input class='big_b' type='submit' value='next' />
</form>";
echo $_SESSION['order'];
?>
You need to put $order++ outside of the quotation marks to make an operation (incrementing by 1). Here's the code:
<?php
$order = $_GET['number'];
echo "<form action='study.php' method='GET'>
<input type='hidden' name='number' value='".$order++."' />
<input class='big_b' type='submit' value='next' />
</form>";
echo "$order";
?>

PHP function to increment variable by 1 each time

I have started writing a PHP script for a game about creatures, there are 4 yes/no questions and what I am trying to do is write a function that will display 2 buttons that say yes and no and give then different names each time I run the function, for example yes1 and no1, then the next time the function is run the names of the buttons will be yes2 and no2.
I have attempted to do this already but it is not working correctly, below is the code I have done so far, any help would be much appreciated.
<?php
session_set_cookie_params(2592000);
session_start();
?>
<html>
<head>
<title>Creature Guessing Game</title>
</head>
<body>
<h1>Creature Guessing Game</h1>
<p> Welcome to the creature guessing game! </p>
<p>Click the button below to start or restart the game </p>
<form method="post" action="Creatures.php">
<input type="submit" name="start" value="Start Game" />
</form>
<?php
$questions = array('Does the creature live on land?', 'Does it have wings?', 'Does it live near water?', 'Can it fly?');
function repeat()
{
$number = 0;
$number++;
echo "<form method ='post' action='Creatures.php'>
<input type='submit' name='yes'.$number value='Yes' />
<input type='submit' name='no'.$number value='No' />
</form>";
}
//If form not submitted, display form.
if (!isset($_POST['start'])){
?>
<?php
} //If form is submitted, process input
else{
switch($_POST)
{
case yes1:
echo $questions[0];
repeat();
break;
case no1:
echo $questions[1];
repeat();
break;
case yes2:
echo $questions[2];
repeat();
break;
case no2:
$questions[3];
repeat();
}
}
?>
</body>
</html>
To do this you need to maintain state between requests.
function repeat() {
$number = $_SESSION['number'];
$number++;
echo "<form method ='post' action='Creatures.php'>
<input type='submit' name='answer' value='Yes' />
<input type='submit' name='answer' value='No' />
</form>";
$_SESSION['number'] = $number;
}
switch
if($_POST['answer']=='Yes') {
switch($_SESSION['number']) {
case 1:
break;
case 2:
break;
}
} else {
switch($_SESSION['number']) {
case 1:
break;
case 2:
break;
}
}
I am not in agreement with the accepted answer:
Here is an easier way to go about it without session:
function repeat() {
static $number = 0;
$number++;
echo "<form method ='post' action='Creatures.php'>
<input type='submit' name='answer' value='Yes' />
<input type='submit' name='answer' value='No' />
</form>";
}
You have to store the 'number' in session or cookie as it will loose the value every time page submitted (reloaded).

Categories