PHP Quiz not working properly - php

I'm trying to make a simple php quiz,but instead of choices I have to insert answers and compare them with strcasecmp() so it won't be a problem if the first letter is uppercase or anything like that,but the code doesn't work properly.Sometimes it doesn't return the correct result,even though I insert the correct answer.
Here is the code:
<?php
$number = rand(1,2);
$result = "";
$answer = "";
$question = "";
$question1 = "What is the capital of China";
$question2 = "What king of country is China?";
$answer1 = "beijing";
$answer2 = "republic";
if ($number == 1) {
$answer = $answer1;
$question = $question1;
}
if ($number == 2) {
$answer = $answer2;
$question = $question2;
}
if(isset($_POST['submit'])){
if (strcasecmp($answer,$_POST['answer']) == 0) {
$result = "Correct!";
} else {
$result = "Wrong!";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form method="post" action="index.php">
<div class="middle">
<p class="question"><?php echo $question;
?></p>
<p class="result"><?php echo $result;
$result = "" ?></p>
<div class="box">
<input type="text" name="answer" placeholder="Type here" class="text">
</div>
</div>
<input type="submit" name="submit" value="Continue" class="btn">
</form>
</body>
</html>

By looking at your code, we can see that when you submit your form, you are restarting the script, which actually resets $random to a new value. With 2 questions, you have 50% chances to have the 'correct' answer, but you would see that your script doesn't work at all with more questions added.
Basically, you should use another way to achieve what you want. You could try to add the id of the question in an hidden <input> and check when your form is submit to determine which one it was.
if(isset($_POST['submit'])){
switch ($_POST['question']) { // Add '{'
case 1:
if (strcasecmp($answer1,$_POST['answer']) == 0) {
$result = "Correct!";
} else {
$result = "Gresit!";
}
break;
case 2:
if (strcasecmp($answer2,$_POST['answer']) == 0) {
$result = "Correct!";
} else {
$result = "Gresit!";
} // Forgot to Add '}'
break;
} // Add '}' It give error in PHP 5.3 Parse error: syntax error, unexpected T_CASE, expecting ':' or '{'
}
For the HTML, you could add this input in your form :
<input type="text" name="question" value="<?php echo $number ?>" hidden>
This is not the best way to achieve what you want, this is just an example of what would work.

Related

How to optimize if else in post method?

I have mainly two question first describe what I going to do. I've created some animal in the code by saying that octopus will have 8 leggs,9 brain,1 stomach,3 heart similarly for other property.And by a html form using post method I'm taking input from user as showing the animals image if the description matches.
I've also declared the corresponding animals name.I want to also show the name of the animal after matching(by printing $name).
2)Here I'm matching user input for each animal(by using if,elseif elseif) but how can I optimize so that if there is more than 100 animal I don't have to do 100 else if.
Here is my code.
<?php
class animal{
var $name;
var $brain;
var $stomach;
public $heart;
public $leg;
function __construct($aBrain, $aStomach, $aHeart, $aLeg)
{
$this->brain = $aBrain;
$this->stomach = $aStomach;
$this->heart = $aHeart;
$this->setLeg($aLeg);
}
function isBipedal(){
if ($this->leg == 2) {
return "it is a bipedal animal";
}else {
return "it is not a bipedal animal";
}
}
function getLeg(){
return $this->leg;
}
function setLeg($leg){
if ($leg == 8 ||$leg == 4 ||$leg == 2) {
$this->leg= $leg;
}else {
$this->leg= "non-pedal";
}
}
}
$octopus = new animal(9,1,3,8);
$cow = new animal(1,4,1,4);
$human = new animal(1,1,1,2);
$octopus->setLeg(8);
//echo "new leg ".$octopus->leg = 0;
echo "<br>".$octopus->getleg();
echo "<br>".$human->isBipedal(). "<br>";
if(isset($_POST['submit'])) {
if(isset($_POST['brain'])
&& isset($_POST['stomach'])
&& isset($_POST['heart'])
&& isset($_POST['leg']) ){
$myBrain = $_POST['brain'];
$myStomach = $_POST['stomach'];
$myHeart = $_POST['heart'];
$myLeg = $_POST['leg'];
// echo "brain = ". $myBrain. "<br>";
// echo "stomach = ". $myStomach. "<br>";
// echo "heart = ". $myHeart. "<br>";
// echo "leg = ". $myLeg. "<br>";
if($myBrain==$octopus->brain
&& $myStomach==$octopus->stomach
&& $myHeart==$octopus->heart
&& $myLeg==$octopus->leg
){
?>
<div class="animal-info">
<div><p class="blinking">You are Octopus</p></div>
<img src="media/octopus.jpg" alt="" class="animal-img">
<img src="media/octopus.gif" alt="" class="animal-img">
</div>
<?php
}
elseif($myBrain==$cow->brain
&& $myStomach==$cow->stomach
&& $myHeart==$cow->heart
&& $myLeg==$cow->leg
){
?>
<div class="animal-info">
<div>
<span class="blinking">You are Cow</span>
</div>
<img src="media/cow.jpg" alt="" class="animal-img">
<img src="media/cow.gif" alt="" class="animal-img">
</div>
<?php
}
elseif($myBrain==$human->brain
&& $myStomach==$human->stomach
&& $myHeart==$human->heart
&& $myLeg==$human->leg
){
?>
<div class="animal-info">
<div>
<span class="blinking">You are Human</span>
</div>
<img src="media/human.jpg" alt="" class="animal-img">
<img src="media/human.gif" alt="" class="animal-img">
</div>
<?php
}else{
echo "you don't match with anything at all";
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form action="" method="post">
<span>How many brain you have?</span>
<input type="text" name="brain" id="brain">
<br>
<span>How many stomach you have?</span>
<input type="text" name="stomach" id="stomach">
<br>
<span>How many heart you have?</span>
<input type="text" name="heart" id="heart">
<br>
<span>How many leg you have?</span>
<input type="text" name="leg" id="leg">
<br>
<input type="submit" name="submit" value="Let me see">
</form>
</body>
</html>
u should either store them in a DB and make a query, or store them in array and search by some linq equivalent in php
Could You try with a Switch case?
<?php
if ($i == 0) {
echo "i equals 0";
} elseif ($i == 1) {
echo "i equals 1";
} elseif ($i == 2) {
echo "i equals 2";
}
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
}
?>

PHP form with multiple steps and validation

I'm new to PHP and I'm trying to create an easy form that has multiple steps. For each step, a validation of the input is happening before the user is directed to the next page. If the validation fails, the user should stay on the same page and an error message should be displayed. In the end, all entries that the user has made should be displayed in an overview page.
What I have been doing to solve this, is to use a boolean for each page and only once this is true, the user can go to the next page. This is not working as expected unfortunately and I guess it has something to do with sessions in PHP... I also guess that there's a nicer way to do this. I would appreciate some help!
Here's my code:
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Test</title>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
session_start();
$_SESSION['$entryOne'] = "";
$_SESSION['$entryOneErr'] = $_SESSION['$emptyFieldErr'] = "";
$_SESSION['entryOneIsValid'] = false;
$_SESSION['$entryTwo'] = "";
$_SESSION['$entryTwoErr'] = "";
$_SESSION['entryTwoIsValid'] = false;
// Validation for first page
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submitEntryOne'])) {
if (!empty($_POST["entryOne"])) {
// Check for special characters
$_SESSION['$entryOne'] = removeWhitespaces($_POST["entryOne"]);
$_SESSION['$entryOneErr'] = testForIllegalCharError($_SESSION['$entryOne'], $_SESSION['$entryOneErr']);
// If error text is empty set first page to valid
if(empty($_SESSION['$entryOneErr'])){
$_SESSION['$entryOneIsValid'] = true;
}
} else {
// Show error if field hasn't been filled
$_SESSION['$emptyFieldErr'] = "Please enter something!";
}
// Validation for second page
} else if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submitEntryTwo'])) {
if (!empty($_POST["entryTwo"])) {
// Check for special characters
$_SESSION['$entryTwo'] = removeWhitespaces($_POST["entryTwo"]);
$_SESSION['$entryTwoErr'] = testForIllegalCharError($_SESSION['$entryTwo'], $_SESSION['$entryTwoErr']);
// If error text is empty set second page to valid
if(empty($_SESSION['$entryTwoErr'])){
$_SESSION['$entryTwoIsValid'] = true;
}
} else {
// Show error if field hasn't been filled
$_SESSION['$emptyFieldErr'] = "Please enter something!";
}
}
//Remove whitespaces at beginning and end of an entry
function removeWhitespaces($data) {
$data = trim($data);
return $data;
}
//Check that no special characters were entered. If so, set error
function testForIllegalCharError($wish, $error){
$illegalChar = '/[\'\/~`\!##\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/';
if (preg_match($illegalChar,$wish)) {
$error = "Special characters are not allowed";
} else {
$error = "";
}
return $error;
}
?>
<?php if (isset($_POST['submitEntryOne']) && $_SESSION['$entryOneIsValid'] && !$_SESSION['$entryTwoIsValid']): ?>
<h2>Second page</h2>
<p>Entry from first Page: <?php echo $_SESSION['$entryOne'];?></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Entry Two: <input type="text" name="entryTwo" value="<?php echo $_SESSION['$entryTwo'];?>">
<span class="error"><?php echo $_SESSION['$entryTwoErr'];?></span>
<br><br>
<input type="submit" name="submitEntryTwo" value="Next">
</form>
<?php elseif (isset($_POST['submitEntryTwo']) && $_SESSION['$entryTwoIsValid']): ?>
<h2>Overview</h2>
<p>First entry: <?php echo $_SESSION['$entryOne'];?></p>
<p>Second Entry: <?php echo $_SESSION['$entryTwo'];?></p>
<?php else: ?>
<h2>First page</h2>
<span class="error"><?php echo $_SESSION['$emptyFieldErr'];?></span>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<br><br>
First entry: <input type="text" name="entryOne" value="<?php echo $_SESSION['$entryOne'];?>">
<span class="error"> <?php echo $_SESSION['$entryOneErr'];?></span>
<br><br>
<input type="submit" name="submitEntryOne" value="Next">
</form>
<?php endif; ?>
</body>
</html>
You are setting your session variables to "" at the top of your script.
Check if your variable is set before setting to blank.
Check if Session Variable is Set First
<?php
//If variable is set, use it. Otherwise, set to null.
// This will carry the variable session to session.
$entryOne = isset($_REQUEST['entryOne']) ? $_REQUEST['entryOne'] : null;
if($entryOne) {
doSomething();
}
?>
Tips
Then you can use <?= notation to also echo the variable.
Do this $_SESSION['variable'] instead of $_SESSION['$variable'] (you'll spare yourself some variable mistakes).
<h2>Second page</h2>
<p>Entry from first Page: <?= $entryOne ?></p>
Example Script
This could be dramatically improved, but for a quick pass:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Check that no special characters were entered. If so, set error
function hasIllegalChar($input){
$illegalChar = '/[\'\/~`\!##\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/';
if (preg_match($illegalChar, $input)) {
return true;
}
return false;
}
session_start();
// Destroy session and redirect if reset form link is pressed.
if(isset($_GET['resetForm']) && $_GET['resetForm'] == "yes")
{
echo "SESSION DESTROY";
session_destroy();
header("Location: ?");
}
// Session
$page = isset($_SESSION['page']) ? $_SESSION['page'] : 1;
$errors = [];
// Value history.
$valueOne = isset($_SESSION['valueOne']) ? $_SESSION['valueOne'] : null;
$valueTwo = isset($_SESSION['valueTwo']) ? $_SESSION['valueTwo'] : null;
// Clean inputs here
$fieldOne = isset($_REQUEST['fieldOne']) ? trim($_REQUEST['fieldOne']) : null;
$fieldTwo = isset($_REQUEST['fieldTwo']) ? trim($_REQUEST['fieldTwo']) : null;
// First form
if ($page == 1) {
// If field two is submitted:
if ($fieldOne) {
//Validate inputs
if(hasIllegalChar($fieldOne)) {
$errors[] = "You entered an invalid character.";
}
if (count($errors) == 0 ){
$valueOne = $_SESSION['valueOne'] = $fieldOne;
$page = $_SESSION['page'] = 2;
}
}
}
// Second form
else if ($page == 2) {
// If field two is submitted:
if ($fieldTwo) {
//Validate inputs
if(hasIllegalChar($fieldTwo)) {
$errors[] = "You entered an invalid character.";
}
if (count($errors) == 0 ){
$valueTwo = $_SESSION['valueTwo'] = $fieldTwo;
$page = $_SESSION['page'] = 3;
}
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Test</title>
<style>
.error {
color: #FF0000;
}
</style>
</head>
<body>
<?php
// troubleshoot
if (true) {
echo "<pre>";
var_dump($_REQUEST);
var_dump($_SESSION);
echo "</pre>";
}
echo "<h1>Page " . $page . '</h1>';
if (count($errors) > 0) {
$errorMsg = implode('<br/>',$errors);
echo '<div class="error">Some errors occurred:<br/>' . $errorMsg . '</div>';
}
?>
<?php if ($page == 3): ?>
<h2>Overview</h2>
<p>First entry: <?= $valueOne;?></p>
<p>Second Entry: <?= $valueTwo;?></p>
Reset
<?php elseif ($page == 2): ?>
<p>Entry from first Page: <?= $valueOne; ?></p>
<form method="post" action="<?= $_SERVER["PHP_SELF"] ?>">
Entry Two: <input type="text" name="fieldTwo" value="<?= $fieldTwo ?>" autofocus>
<br><br>
<input type="submit">
</form>
<?php else: ?>
<form method="post" action="<?= $_SERVER["PHP_SELF"] ?>">
<br><br>
Entry One: <input type="text" name="fieldOne" value="<?= $fieldOne; ?>" autofocus>
<br><br>
<input type="submit">
</form>
<?php endif; ?>
</body>
<html>
You can run the following command to test out the page without using a fancy tool like WAMP or LAMP.
php -S localhost:8000 index.php
You can now access in the browser at http://localhost:8000.

Counter not increasing more than one time

I wanted to make specific letter counter, but my counter is not increasing more that once. Can some one explain what i'm doing wrong?
Here is my code:
PHP:
<?php
$count_s = 0;
$count_v = 0;
$input = '';
if(filter_has_var(INPUT_POST, 'submit')) {
if($_SERVER["REQUEST_METHOD"] == "POST") {
$input = $_POST['inp'];
switch($input) {
case 'v':
$count_v++;
case 's':
$count_s++;
}
}
}
?>
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h3>Enter Symbol: </h3>
<form action="index.php" method="POST">
<input type="text" class="input" name='inp' maxlength="1" >
<button class="btn" type="submit" name="submit">Submit</button>
</form>
<div class="output">
<?php
echo "Count of letter 'V': ".$count_v."<br/>";
echo "Count of letter 'S': ".$count_s."<br/>";
?>
</div>
</body>
</html>
Try this it will be work perfectly. paste it in any test file. This will retain no of times you input v and no of times you input s, value of s and v will remain same of input some other value.
<?php
$input = '';
if(!isset($count_v))
{
$count_v=0;
}
if(!isset($count_s))
{
$count_s=0;
}
if (filter_has_var(INPUT_POST, 'submit'))
{
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$input = $_POST['inp'];
switch ($input)
{
case 'v':
$_POST['count_v']++;
$count_v=$_POST['count_v'];
$count_s=$_POST['count_s'];
break;
case 's':
$count_v=$_POST['count_v'];
$_POST['count_s']++;
$count_s=$_POST['count_s'];
break;
default:
$count_v=$_POST['count_v'];
$count_s=$_POST['count_s'];
break;
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h3>Enter Symbol: </h3>
<form method="POST">
<input type="hidden" name='count_v' value="<?php echo $count_v?>">
<input type="hidden" name='count_s' value="<?php echo $count_s?>">
<input type="text" class="input" name='inp' maxlength="1" >
<button class="btn" type="submit" name="submit">Submit</button>
</form>
<div class="output">
<?php
echo "Count of letter 'V': " . $count_v . "<br/>";
echo "Count of letter 'S': " . $count_s . "<br/>";
?>
</div>
</body>
</html>
you need to store counters in each request, because the variables lifetime is short (request life time), then they will be re-init from 0
to do this you can store the counters in file, database, or session
it depends on the time you want them to persist.
below is a sample for using session
** note the new line session_start(); you need to add it.
<?php
session_start();
$count_s = 0;
$count_v = 0;
$input = '';
if(filter_has_var(INPUT_POST, 'submit')) {
if($_SERVER["REQUEST_METHOD"] == "POST") {
$input = $_POST['inp'];
switch($input) {
case 'v':
if(!isset($_SESSION["count_v"])){
$_SESSION["count_v"] = 0;
}
$tmp = $_SESSION["count_v"];
$tmp++;
$_SESSION["count_v"] = $tmp;
break;
case 's':
if(!isset($_SESSION["count_s"])){
$_SESSION["count_s"] = 0;
}
$tmp = $_SESSION["count_s"];
$tmp++;
$_SESSION["count_s"] = $tmp;
break;
}
}
}
?>
and to read the values (in html page) use this:
<?php
echo "Count of letter 'V': ".$_SESSION["count_v"]."<br/>";
echo "Count of letter 'S': ".$_SESSION["count_s"]."<br/>";
?>
if you are going to store more than the 2 letters (s and v) then you can make the session key "count_v" generated dynamically using input itself. this will be a much less code, you will not need a switch/case
Edit: as i saw in your comment above, yes you can maintain counter values using hidden fields in HTML page, and use them to initialize the $count_s and $count_v instead of zero. you need to take care of first request when hidden values might be unset, or they could be zero

How can I change an array value with a click?

I've seen references to Ajax for this, but I'm not entirely sure how I could integrate that with the arrays and still have a functioning system. I want to change the value of $place and $title each time a user presses the button, and I know that I'll need an if statement and some way of processing a form (no clicks in PHP), but I don't know anything else beyond that. I've pasted my PHP and the HTML button below:
<!DOCTYPE html>
<html>
<head>
<title>StatsCalc V1</title>
<link rel="stylesheet" type="text/css" href="sheen.css">
<link rel="script" type="text/javascript" href="slide.js">
<link rel="icon" type="image/png" href="favicon.ico">
<link href='http://fonts.googleapis.com/css?family=Raleway:500' rel='stylesheet' type='text/css'>
</head>
<body>
<?php
$place = 0;
$title = 0;
echo '<div class="boxes"><h1>Statistics Calculator: Version 1</h1></div>';
$links = array('<div class="fancyBoxes"><img class="mainPic" src="normalDist.svg" alt="a normal distribution, courtesy openclipart.org"></div>', "", "");
echo $links[$place];
/*if($_GET){
if(isset($_GET['clickies'])){
$place = 1;
$title = 1;
}
}*/
if($_POST['clickies'] and $_SERVER['REQUEST_METHOD'] == "POST"){
$place = 1;
$title = 1;
}
$subtitle = array('<div class="boxes"><h1>Standardised Score</h1></div>', '<div class="boxes"><h1>Standard Deviation</h1></div>', '<div class="boxes"><h1>Averages</h1></div>');
echo $subtitle[$title];
?>
<input type="submit" id="clickies" name="clickies" value="" />
<script src="move.js"></script>
<script src="slide.js"></script>
<script src="jquery-1.11.2.js"></script>
<!--The calculator must be able to field standardised score, standard deviation, and averages (mean/median/mode)-->
<!--Headings will be assigned with an array; slides will be navigated with tabs on either side of the window-->
<!--Credit to https://openclipart.org/detail/171055/normal-distn-shaded-outside-1s-by-oderwald-171055 for the Standardised Score image/label thingy-->
</body>
</html>
maybe this could give you idea on how to do it.
if($_SERVER['REQUEST_METHOD'] == "POST") {
if (isset($_POST['clickies'])) {
$count = intval($_POST['count']);
$count++;
$place = $count;
$title = $count;
}
} else {
$place = 0;
$title = 0;
}
echo '<div class="boxes"><h1>Statistics Calculator: Version 1</h1></div>';
$links = array('<div class="fancyBoxes"><img class="mainPic" src="normalDist.svg" alt="a normal distribution, courtesy openclipart.org"></div>', "", "");
echo $links[$place];
echo $place; echo "<br/>";
$subtitle = array('<div class="boxes"><h1>Standardised Score</h1></div>', '<div class="boxes"><h1>Standard Deviation</h1></div>', '<div class="boxes"><h1>Averages</h1></div>');
echo $subtitle[$title];
?>
<form action="" method="POST">
<input type="submit" id="clickies" name="clickies" value="" />
<input type="hidden" id="count" name="count" value="<?php echo $place;?>" />
</form>
what I did is need to put the button inside a form and put a method= post
and make it submit it to the same page
i also store the count in a hidden input and pass it always when the form is submitted and update its value on the form,
try to modify according to your need
<?php
$_SESSION["place"] = 0;
$place = 0;
$title = 0;
session_start();
echo '<div class="boxes"><h1>Statistics Calculator: Version 1</h1></div>';
$links = array('<div class="fancyBoxes"><img class="mainPic" src="normalDist.svg" alt="a normal distribution, courtesy openclipart.org"> </div>', "", "");
if($_POST['clickies'] and $_SERVER['REQUEST_METHOD'] == "POST"){
$_SESSION["place"] = $_SESSION["place"] + 1;
$title = 1;
}
echo $links[$_SESSION["place"]];
$subtitle = array('<div class="boxes"><h1>Standardised Score</h1></div>', '<div class="boxes"><h1>Standard Deviation</h1></div>', '<div class="boxes"><h1>Averages</h1></div>');
echo $subtitle[$title];
?>
<form method="post" action="">
<input type="submit" id="clickies" name="clickies" value="submit" />
</form>
you can use session of php.

(PHP) Adding a 'guess counter' to a random number game

I need to modify a block of code and add a counter regarding how many times it took the user to guess the right number.
I was wondering how it would be properly implemented into my code.
This is what I have so far.
<?php
if (!isset($_POST["guess"])) {
$message = "Welcome to the guessing machine!";
$count++; //Declare the variable $count to increment by 1.
$_POST["numtobeguessed"] = rand(0,1000);
} else if ($_POST["guess"] > $_POST["numtobeguessed"]) { //greater than
$message = $_POST["guess"]." is too big! Try a smaller number.";
} else if ($_POST["guess"] < $_POST["numtobeguessed"]) { //less than
$message = $_POST["guess"]." is too small! Try a larger number.";
} else { // must be equivalent
$message = "Well done! You guessed the right number in ".$count." attempt(s)!";
//Include the $count variable to the $message to show the user how many tries to took him.
}
?>
<html>
<head>
<title>A PHP number guessing script</title>
</head>
<body>
<h1><?php echo $message; ?></h1>
<form action="" method="POST">
<p><strong>Type your guess here:</strong>
<input type="text" name="guess"></p>
<input type="hidden" name="numtobeguessed"
value="<?php echo $_POST["numtobeguessed"]; ?>" ></p>
<p><input type="submit" value="Submit your guess"/></p>
</form>
</body>
</html>
You have to use PHP Sessions to keep track of the count.
All you have to do is initialize counter to 0 and have it increment when the user guesses a number
<?php
session_start();
if (!isset($_POST["guess"])) {
$_SESSION["count"] = 0; //Initialize count
$message = "Welcome to the guessing machine!";
$_POST["numtobeguessed"] = rand(0,1000);
echo $_POST["numtobeguessed"];
} else if ($_POST["guess"] > $_POST["numtobeguessed"]) { //greater than
$message = $_POST["guess"]." is too big! Try a smaller number.";
$_SESSION["count"]++; //Declare the variable $count to increment by 1.
} else if ($_POST["guess"] < $_POST["numtobeguessed"]) { //less than
$message = $_POST["guess"]." is too small! Try a larger number.";
$_SESSION["count"]++; //Declare the variable $count to increment by 1.
} else { // must be equivalent
$_SESSION["count"]++;
$message = "Well done! You guessed the right number in ".$_SESSION["count"]." attempt(s)!";
unset($_SESSION["count"]);
//Include the $count variable to the $message to show the user how many tries to took him.
}
?>
<html>
<head>
<title>A PHP number guessing script</title>
</head>
<body>
<h1><?php echo $message; ?></h1>
<form action="" method="POST">
<p><strong>Type your guess here:</strong>
<input type="text" name="guess"></p>
<input type="hidden" name="numtobeguessed"
value="<?php echo $_POST["numtobeguessed"]; ?>" ></p>
<p><input type="submit" value="Submit your guess"/></p>
</form>
</body>
</html>
This should work for you.
$count = isset($_POST['count']) ? $_POST['count'] : 0; //Use post value if defined. If not set to 1.
if (!isset($_POST["guess"])) {
$message = "Welcome to the guessing machine!";
$_POST["numtobeguessed"] = rand(0,1000);
} else if ($_POST["guess"] > $_POST["numtobeguessed"]) { //greater than
$message = $_POST["guess"]." is too big! Try a smaller number.";
} else if ($_POST["guess"] < $_POST["numtobeguessed"]) { //less than
$message = $_POST["guess"]." is too small! Try a larger number.";
} else { // must be equivalent
$message = "Well done! You guessed the right number in ".$count." attempt(s)!";
//Include the $count variable to the $message to show the user how many tries to took him.
}
$count++;
?>
<html>
<head>
<title>A PHP number guessing script</title>
</head>
<body>
<h1><?php echo $message; ?></h1>
<form action="" method="POST">
<p><strong>Type your guess here:</strong>
<input type="text" name="guess"></p>
<input type="hidden" name="numtobeguessed"
value="<?php echo $_POST["numtobeguessed"]; ?>" ></p>
<input type="hidden" name="count"
value="<?php echo $count; ?>" ></p>
<p><input type="submit" value="Submit your guess"/></p>
</form>
</body>
</html>
on 22.6.2021 i wrote a Guess Number in Range [0 .. aMaxIntValue] sample Web Application using PHP. i think the following code may help you. the code is kept in a Single PHP file. it generates #4 HTML pages ...
the 1st initial page is used to collect application parameters (e.g. the Max Int Number to Guess)
the 2nd page is the Main Play Game Page where the user is asked to Guess the Secret Number or to Reset Game. this page shows the previous user guesses and some tips for the user about the guess
the 3rd page is used to notify the user looses game (that is he has no more tries left)
the 4th page is used to notify the user wins the game (that is the Guess was OK)
the Number of Tries left to the User is computed using the values range [0 .. max]
the Secret Number to Guess is a random generated integer number
this is the PHP + HTML code ...
<?php
session_start();
error_reporting (E_PARSE | E_COMPILE_ERROR);
function ResetGame()
{
unset ( $_SESSION['theMaxNumber'] );
}
function InitGame()
{
$_SESSION['theNumberToGuess'] = mt_rand (0, $_SESSION['theMaxNumber']);
$_SESSION['theMaxNumberOfTries'] = floor ( log ($_SESSION['theMaxNumber'], 2) ) + 1;
$_SESSION['theUserTriesCount'] = 0;
$_SESSION['thePrevGuessesString'] = '';
$_SESSION['theUserGuess'] = 0;
}
function ComputeNumberOfTriesLeft()
{
return $_SESSION['theMaxNumberOfTries'] - $_SESSION['theUserTriesCount'];
}
function IsNoMoreTriesLeft()
{
return ComputeNumberOfTriesLeft() <= 0;
}
$aCanPlayGame = false;
$aUserSubmittedGuess = false;
$aIsNoMoreTriesLeft = false;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ( isset ($_REQUEST['playgame']) ) {
$_SESSION['theMaxNumber'] = intval($_REQUEST['theMaxNumber']);
// init game ...
InitGame();
$aCanPlayGame = true;
}
elseif ( isset ($_REQUEST['submituserguess']) ) {
$aCanPlayGame = true;
$aUserSubmittedGuess = true;
$_SESSION['theUserGuess'] = intval($_REQUEST['theUserGuess']);
}
elseif ( isset ($_REQUEST['resetgame']) ) {
ResetGame();
}
else {
ResetGame();
}
}
else {
ResetGame();
}
// check a play
$aUserShouldTryLower = false;
$aUserShouldTryHigher = false;
$aUserWins = false;
$aUserLooses = false;
if ($aCanPlayGame) {
$aIsNoMoreTriesLeft = IsNoMoreTriesLeft();
if ( ! $aIsNoMoreTriesLeft ) {
// user have tries left
if ($aUserSubmittedGuess) {
// check user guess ...
$aUserGuess = intval($_SESSION['theUserGuess']);
if ( $aUserGuess > $_SESSION['theNumberToGuess'] ) {
$aUserShouldTryLower = true;
}
elseif ( $aUserGuess < $_SESSION['theNumberToGuess'] ) {
$aUserShouldTryHigher = true;
}
else {
$aUserWins = true;
// also reset game
ResetGame();
}
// add the current guess to the prev guesses string
$_SESSION['thePrevGuessesString'] .= $_SESSION['theUserGuess'] . ' ';
// increase the user tries count
++ $_SESSION['theUserTriesCount'];
// check tries count
if ( ! $aUserWins ) {
$aIsNoMoreTriesLeft = IsNoMoreTriesLeft();
if ($aIsNoMoreTriesLeft) {
// this was the last try
// no more tries left
$aUserLooses = true;
// also reset game
ResetGame();
}
}
}
}
else {
// no more tries left
$aUserLooses = true;
// also reset game
ResetGame();
}
}
?>
<?php if ($aUserLooses): ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>Sorry, you loose the game</p>
<p>the Number to Guess was <?php echo $_SESSION['theNumberToGuess']; ?></p>
<form method="post">
<input type="submit" name="resetgame" value="reset game">
</form>
</body>
</html>
<?php elseif ($aUserWins): ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>Congrats, you Win the Game</p>
<p>the Number to Guess was <?php echo $_SESSION['theNumberToGuess']; ?></p>
<form method="post">
<input type="submit" name="resetgame" value="reset game">
</form>
</body>
</html>
<?php elseif ($aCanPlayGame): ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>the Max Number is <?php echo $_SESSION['theMaxNumber']; ?></p>
<p>Guess a Number in the Range [ 0 .. <?php echo ($_SESSION['theMaxNumber']); ?> ]</p>
<p>[DEBUG] the secret number to guess is <?php echo $_SESSION['theNumberToGuess']; ?></p>
<p>you have <?php echo ComputeNumberOfTriesLeft(); ?> tries left</p>
<form method="post">
<label for="theUserGuess">Enter your Guess: </label>
<input type="text" id="theUserGuess" name="theUserGuess">
<input type="submit" name="submituserguess" value="Guess">
<input type="submit" name="resetgame" value="reset game">
</form>
<p>Prev Guesses: <?php echo $_SESSION['thePrevGuessesString']; ?> </p>
<p>
<?php
if ($aUserShouldTryLower) {
echo 'you should try a lower < guess';
}
elseif ($aUserShouldTryHigher) {
echo 'you should try a higher > guess';
}
else {
echo 'no guess';
}
?>
</p>
</body>
</html>
<?php else: ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>Guess a Number from (0) to ... </p>
<form method="post">
<input id="theMaxNumber" name="theMaxNumber">
<input type="submit" name="playgame" value="play game">
</form>
</body>
</html>
<?php endif; ?>
that's all folks ...

Categories