Simple PHP quiz using a text box input - php

I'm looking to implement a very simple quiz using PHP which I'm struggling to find any other examples of to copy. I'm open to various solutions but the requirements are as follows:
Quiz takes place on a single page;
One questions appears at a time, and the user can only see the next question when they correctly answered the current one;
All question types are 'short answer', with users needing to input the correct answer in a text box.
I have been attempting to find a solution using PHP conditional statements (if/else) based on a users answers and my current code looks like this:
<form method="POST" action="">
<label for="question01">1. How many sides does a triangle have?</label>
<input type="text" name="guess01" value="">
<input type="submit">
</form>
<?php
// Process Question 1 Form
$guess01 = $_POST['guess01'];
$guess01 = strtolower($guess01);
$answer01 = "three";
if ($guess01 == $answer01)
{
?>
<p>Correct answer given for question 1!</p>
<form method="POST" action="">
<label for="question02">2. How many sides does a square have?</label>
<input type="text" name="question02" value="" placeholder="Answer here...">
<input type="submit">
</form>
<?php
// Process Question 2 Form
$guess02 = $_POST['guess02'];
$guess02 = strtolower($guess02);
$answer02 = "four";
if ($guess02 == $answer02)
{
?>
<p>Correct answer given for question 2!</p>
<form>
<label for="question02">3. How many sides does a pentagon have?</label>
<input type="text" name="question02" value="" placeholder="Answer here...">
<input type="submit">
</form>
<?php
// Process Question 2 Form
$guess03 = $_POST['guess02'];
$guess03 = strtolower($guess02);
$answer03 = "five";
if ($guess03 == $answer03)
{
?>
<p>Correct answer given for question 3!</p>
<p>Quiz completed!</p>
<?php
}
elseif (empty($guess03))
{
echo "<!-- No Answer Given -->";
}
else
{
echo "<p>Try Again!</p>";
}
?>
<?php
}
elseif (empty($guess02))
{
echo "<!-- No Answer Given -->";
}
else
{
echo "<p>Try Again!</p>";
}
?>
<?php
}
elseif (empty($guess01))
{
echo "<!-- No Answer Given -->";
}
else
{
echo "<p>Try Again!</p>";
}
?>
I'm sure this is very inefficient coding and I'm open to other ways of tackling this. Any help would be very gratefully received. Thank you.

As the form and the validation of your questions are always same only the data changes, you do not need to copy the code. Just put questions and answers in an array and put the number of the current questions in your form.
// Declare all your questions and answers as multi dimensional array
$questionsAndAnwsers = array(array("question" => "1. How many sides does a triangle have?", "answer" => "three"),
array("question" => "2. How many sides does a square have?", "answer" => "four"));
// current question
$currentQuestion = 0;
if(isset($_POST["currentQuestion"])){
$currentQuestion = $_POST["currentQuestion"];
if($_POST["guess"] == $questionsAndAnwsers[$currentQuestion]["answer"]){
// answer was correct, increment your question-counter for the next question
$currentQuestion++;
// print success message
} else {
// question was wrong, counter stays as it is, so same question will be printed
// print failure message
}
}
?>
<form method="POST" action="">
<label for="question"><?php echo ($currentQuestion+1).". ". $questionsAndAnwsers[$currentQuestion]["question"];?></label>
<input type="hidden" name="currentQuestion" value="<?php echo $currentQuestion;?>">
<input type="text" name="guess" value="">
<input type="submit">
</form>
<?php
You have to add a additional if-clause, for the case all questions has been answered.
EDIT:
This is a simple Implementation and it is easy to cheat. As the question number is passed to the browser, the user can alter it (setting it to 9). To close this whole, you have to use session and save the number of the last correct answer in the session on the server.

Related

php allow submit if variable is true

Newbie here, and self-taught in PHP. I have a questionnaire where each question has 2 answers, and users can add any combination of numbers to each, as long as they equal, i.e. 10. So far 2 questions (will be more) so each question's answers should equal 10, therefore total submitted values should equal 20. I can't find a way to only allow submit if these conditions are met. I would really appreciate any help.
Currently using this for testing purposes:
<input type="submit" value="Check!" name="check"/>
...at the bottom.
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<?php
// Adding stuff
if(isset($_POST['check']))
{
$q1total=$realist[1]+$idealist[1];
$q2total=$realist[2]+$idealist[2];
$grandtotal=$q1total+$q2total;
}
?>
<body>
<form method="post">
Q1: <input type="text" name="realist[1]"/> <input type="text" name="idealist[1]"/>
<?php echo $q1total; ?>
<br>
Q2: <input type="text" name="realist[2]"/> <input type="text" name="idealist[2]"/>
<?php echo $q2total; ?>
<br>
<br><br>
Grand total: <?php echo $grandtotal; ?>
<br><br>
<input type="submit" value="Check!" name="check"/>
</form>
</body>
</html>
I'm also a self-taught PHP "newbie" as you describe it. I would honestly create a seperate PHP file that checks if the conditions are met.
Your form would be:
<form method="post" action="yourfile.php">
And in the php file:
$realist1 = $_POST["realist\[1\]"];
$idealist1 = $_POST["idealist\[1\]"];
$realist2 = $_POST["realist\[2\]"];
$idealist2 = $_POST["idealist\[2\]"];
if ($realist[1]+idealist[1]== 10 && $realist[2]+idealist[2] == 10)
{
echo "<button value='correct'/>";
}else{
echo "<button value='incorrect' disabled/>";
}
Obviously you have to adjust some stuff but hopefully this can help.

How to set form input data to equal specific strings in a PHP If Else Statement? [duplicate]

This question already has answers here:
The 3 different equals
(5 answers)
Closed 6 years ago.
I'm having trouble with this for some reason. Basically i'm trying to make it so that one person can go through. If the users name is equal to "Megan" "Renae" then the output will be Hello, "Megan" "Renae" but if there is anything else I want it to output I do not know you. I know this is probably something extremely simple and it is just going over my head but if someone could help you would stop my hair from turning grey! Thank you in advance to anyone that responds.
<form method = "POST" action = " ">
<p>Please enter your first name: <input type="text" name="fName"><br>
<p>Please enter your last name: <input type="text" name="lName"><br><br>
<input type="submit" class="btnSubmit" name="submit"></p>
</form>
<?php
if ($_POST['submit'] != "") {
if ($_POST['fName'] = "Megan") {
if ($_POST['lName'] = "Renae") {
echo "<p>Hello, Megan Renae</p>"; }
else {
echo "<p>I do not know you</p>";
}}}
?>
This is the PHP snippet you are looking for:
<?php
if ($_POST['fName'] == 'Megan' && $_POST['lName'] == 'Renae') {
echo '<p>Hello, Megan Renae</p>';
}
else {
echo '<p>I do not know you</p>';
}
?>
In the if statements where you have $_POST[...] = 'some value' you need to use == to compare the values instead of = which sets the value of the variable.

confused about basic find and replace app

I am trying to do a find and replace applicaiton the problem is that after cliked submit button all the text fields gets clean nothing displays on the screen What am i doing wrong
<?php
$offset=0;
if(isset($_POST['text'] ) && isset($_POST['searchfor']) && isset($_POST['replacewith'])){
$text=$_POST['text'];
$search=$_POST['searchfor'];
$replace=$_POST['replacewith'];
$searchLength=strlen($search);
if(!empty($text) && !empty($search) &&!empty($replace)){
while ($strpos= strpos($text,$search,$offset)){
echo $offset=$strpos+$searchLength;
}
} else {
echo "<script>alert('errorrrr')</script>";
}
}
?>
<form action="#" method="post">
<textarea name="text" id="" cols="30" rows="10"></textarea><br>
Search For:<br>
<input type="text" name="searchfor"><br>
ReplaceWith<br>
<input type="text"name="replacewith"><br>
<input type="submit" value="Fr..."></>
</form>
Regarding your form, you decided to submit to the same page.
Doing this, the page is obviously fully reloaded when submitted. Hence it is normal that what you typed in has disappeared.
If you want to see it again, you have to display you variables in the HTML code.
For example:
<?php
$myVar = "";
if(isset($_POST['myVar']){
$myVar = $_POST['myVar'];
}
?>
<form>
<input type="text" value="<?php echo $myVar;?>"/>
</form>
NB: I encourage you to filter the user entry.
Regards
there is problems in your code :
1 - echo $offset=$strpos+$searchLength; the echo can't be used in this format. insted use echo $offset; in next line for seeing offset values.
2 - if the text be like 'amir love persepolis' and search for 'amir' to replace it with 'all men's' you will have another issue, because you will have while ( 0 ) situation. think about this too!

PHP How to check if text field matches var

Well then, this is likely to be the n-th time someone is asking this, but honestly I didn't grab anything useful spending the last hour or so on Google. What I want to do is rather trivia, or so I thought. I have this working in Java Script but want to move it to PHP. In brief:
declare a var with a static value
add text field into which user is asked to enter value of above var
check if field is a) empty, b) non-empty mismatch, or c) non-empty match
My (limited) PHP wisdom has lead me into believing it ought to be something like the below, but apparently it's not. I'd very much appreciate any insight, tha.
<?php
$coconew = "blah";
if (isset ($_POST["cocosub"])) {
if ($_POST["cocoval"] == "") {
echo "empty";
} else {
if ($_POST["cocoval"] != $coconew) {
echo "mismatch";
} else {
echo "match";
}
}
}
?>
<form action="<?php $_SERVER['PHP_SELF'] ?>" id="cocosub" method="post">
<div>
<?php echo $coconew; ?>
<input type="text" id="cocoval">
<input type="submit">
</div>
</form>
You need to change
<input type="text" id="cocoval">
to
<input type="text" name="cocoval">
There are other (and probably better) ways to do this, but you are on the right track.
$_POST only looks for the name attribute of form elements, so modify your form as such:
<?php
$coconew = "blah";
if (isset ($_POST["cocoval"])) {
if ($_POST["cocoval"] === "") {
echo "empty";
} else {
if ($_POST["cocoval"] !== $coconew) {
echo "mismatch";
} else {
echo "match";
}
}
}
?>
<form id="cocosub" method="post">
<div>
<?php echo $coconew; ?>
<input type="text" id="cocoval" name="cocoval">
<input type="submit">
</div>
</form>
(I made a few other changes, you want to check isset on the element, not the form, it will POST to the same page if you don't give it an attribute [so no need to add the echo], and adding better type checking in your php)
in addition to the other answers already posted, you might also be interested in PHP's session support (depending on how "static" you need your static variables to be). That's where you'd put $cocoval and any other variables if you need to save their values across multiple requests for the same URL by the same user. See here for more info:
http://php.net/manual/en/features.sessions.php and
http://www.php.net/manual/en/book.session.php
This works:
<?php
session_start();
if(isset($_POST["cocosub"])){
$input = trim($_POST["cocoval"]);
if($input == ""){
echo "empty";
} elseif($input != $_SESSION["coconew"]){
echo "mismatch";
} else {
echo "match";
}
}
$_SESSION["coconew"] = substr(md5(uniqid()), 0, 5);
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" id="cocosub" method="post">
<div>
<?php echo $_SESSION["coconew"]; ?>
<input type="text" id="cocoval" name="cocoval">
<input type="submit" name="cocosub">
</div>
</form>
You needed to add name="cocosub" to the Submit button element in order for the first if(isset(...)) condition to be true. That's why the script didn't work. Also, instead of id, you need to use the name="cocoval" in the input text field as well in order for it to carry over into $_POST.

Using a function a dynamic amount of times [duplicate]

This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
How to loop through dynamic form inputs and insert into an array
I have a php script and a form. The php script makes an xml file but what i need is for someone to enter a number and that would set that amount of textboxes that would be for someone to write data for that xml file.
So i need it to write <input type="text" name="a #"> however many times the user enters. Also the name needs to be a number but it counts by one ex:<input type="text" name="1"> <input type="text" name="2">... Thanks
<?php
session_start();
if(isset($_POST['quantity']){
// code here to check isnum and min/max
$count = $_POST['quantity'];
for ($i=1; $i<=$count; $i++){
#$s.= "<input type=text name=".$i."><br>";
}
?>
now just echo out $s in your html
This?
<form method="get" action="">
<div><input type="text" name="num_inputs" value="1" placeholder="Number of inputs"/></div>
</form>
<?php $num_inputs = isset($_GET['num_inputs']) ? $_GET['num_inputs'] : 1; ?>
<form method="post" action="">
<?php for ($i = 0; $i < $num_inputs; $i++) : ?>
<div><input type="text" name="inputs[]"/></div>
<?php endfor ?>
</form>
Edit: yes, an array is much better than input_x. Updated my answer.
I think what you want is an array of form fields.
You want something like this:
<?php
$number_of_textboxes = 5; // you'd get this from a $_GET parameter
echo str_repeat('<input type="text" name="mybox[]" />', $number_of_textboxes);
?>
This will print five text boxes:
<input type="text" name="mybox[]" />
Then, when you reference these boxes' values, you do so like thus:
<?php
foreach ($_POST['mybox'] as $i) {
echo $i;
}
?>
That is, by using "mybox[]" as the name of each input field, you create an array of textboxes, which you can then iterate through.

Categories