PHP repeating output - php

For some reason, my code is only outputting 'p3' and 'p4' twice. I was wondering if anyone could point out why it's repeating, and it'd be appreciated. Here's an example of what is wrong (this only is on p3 and p4 as stated above, p1 and p2 work fine)
http://i.imgur.com/glNXwr7.png
Here's my code:
index.php -
<?php
session_start();
if (!isset($_SESSION['p']))
{
$_SESSION['p'] = 'p1';
}
include('core.php');
include('core2.php');
$story = new Story;
$action = new Action;
$part = $_SESSION['p'];
?>
<!DOCTYPE HTML>
<html>
<head>
<title>MacBeth Console</title>
<style>
body{
background:black;
color:#2ecc71;
font-family: "Courier New", Courier, monospace
}
.txt{
border:0px;
background-color:black;
color:#2ecc71;
font-family: "Courier New", Courier, monospace
}
input:focus {outline: none; }
</style>
</head>
<body>
<?php
echo 'DEBUG: P_'.$part.' <br />';
if ($_SESSION['p'] == 'p1')
$story->p1();
else
$action->continueStory($part, '');
if (isset($_POST['submit']))
{
$action->ContinueStory($part, $_POST['yourAction']);
}
?>
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="hidden" name="p" value="<?php echo $part; ?>" style="vertical-align:middle;">
<img src="cmd.png"><input type="text" id="input" name="yourAction" class="txt">
<input type="submit" name="submit" value="continue">
</form>
</body>
</html>
core.php -
<?php
class Story
{
public function p1()
{
print '<b>Witch 1</b>: When shall we all meet again? <br />
<b>Witch 2</b>: When the hurly-burly is done, and the battle\'s lost and won. <br />
<b>Witch 3</b>: That will be ere the set of sun. <br />
<b>Witch 1</b>: Where\'s the place? <br />
<b>Witch 2</b>: Upon the heath, is this location to thou satisfaction? <br />';
}
public function p2($action)
{
$action = strtolower($action);
if ($action == 'yes')
{
$_SESSION['p'] = 'p3';
print '** The meeting shall be held upon the heath to meet with MacBeth. ** -- PRESS ENTER';
}
else if ($action == 'no')
{
$_SESSION['p'] = 'p3';
print '** Despite your opinion, the other witches decide the best place to meet would be at the heath. **';
}
else
{
print 'Unknown action "'.$action.'".';
}
}
public function p3($action)
{
echo 'test ';
$_SESSION['p'] = 'p4';
/*return '<b><i>Scene II</i></b> <br />
<b>Duncan</b>: What bloody man is that? He can report, as seemeth by his plight, of the revolt the newest state. <br /> <br />
<b>Sergent</b>: Doubtful it stood; As two spent swimmers, that do cling together, and choke their art. The merciless Macdonwald-- Worthy to be a rebel, for to that
The multiplying villanies of nature. Do swarm upon him--from the western isles of kerns and gallowglasses is supplied; and fortune, on his damned quarrel smiling,
Show\'d like a rebel\'s whore: but all\'s too weak: For brave Macbeth--well he deserves that name-- Disdaining fortune, with his brandish\'d steel,
which smoked with bloody execution like valour\'s minion carved out his passage till he faced the slave; Which ne\'er shook hands, nor bade farewell to him
till he unseam\'d him from the nave to the chaps and fix\'d his head upon our battlements.
<b>Duncan</b>: O valiant cousin! worthy gentleman! <br /> <br />
** Please press enter ** <br />';*/
}
public function p4($action)
{
$_SESSION['p'] = 'p1';
echo 'test 2';
}
}
?>
core2.php -
<?php
class Action
{
public function ContinueStory($p, $action)
{
$story = new Story;
if ($p == "p1")
{
$story->p2($action);
}
else if ($p == "p3")
{
$story->p3($action);
}
else if ($p == "p4")
{
$story->p4($action);
}
}
}
?>

Your problem is here :
<?php
echo 'DEBUG: P_'.$part.' <br />';
if ($_SESSION['p'] == 'p1')
$story->p1();
else
$action->continueStory($part, '');
if (isset($_POST['submit']))
{
$action->ContinueStory($part, $_POST['yourAction']);
}
?>
You're doing
$action->continueStory($part, '');
twice. First in your first 'if else', and secondly in your "if isset $_POST".
This should be the best way :
<?php
echo 'DEBUG: P_'.$part.' <br />';
if (isset($_POST['submit']))
{
$action->ContinueStory($part, $_POST['yourAction']);
} else {
if ($_SESSION['p'] == 'p1')
$story->p1();
else
$action->continueStory($part, '');
}
?>
N.B. : For security purpose, don't use $_SERVER['PHP_SELF'] in your form action, just #_ should be better I think!

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;
}
?>

Change empty input border after submission

I want to have it so if the person clicks the submit button and leaves a input / textarea empty. I want it to change the now gray border to red (Whichever input was left empty).
My current code:
if(empty($_POST['email']) ||
empty($_POST['name']) ||
empty($_POST['message']) ||
empty($_POST['pref-job']) ||
empty($_POST['username']))
{
echo "<style type='text/css'>
input {
border: thin solid #e51923;
}
textarea {
border: thin solid #e51923;
}
</style>";
}
You can do this with php, but a much better option is to use HTML5.
The required attribute will stop submission and highlight the field red if it is not populated.
<input type="email" name="email" required="required" />
Note that this will only function correctly with those browsers that implement HTML5, and should not be relied upon for validation. You should still validate server side. In this case, I would suggest adding a class to the input field to show that it is invalid in php - something like:
if (empty($_POST['email'])) {
$emailClass = 'validationFailed';
} else {
$emailClass = '';
}
printf('<input type="email" name="email" class="%s" />', $emailClass);
For this to work, you would also need the validationFailed class to have been defined of course - something like in your question:
.validationFailed {
border: thin solid #e51923;
}
Since Both HTML require and PHP empty() can be bypassed my space
$email = null;
$name = null;
$message = null;
$pref_job = null;
$username = null;
if ($_POST) {
$error = false;
if(trim($_POST['email']) == false) {
$email = 'failed';
$error = true;
}
if (trim($_POST['name']) == false) {
$name = 'failed';
$error = true;
}
if (trim($_POST['message']) == false) {
$message = 'failed';
$error = true;
}
if (trim($_POST['pref_job']) == false) {
$pref_job = 'failed';
$error = true;
}
if (trim($_POST['username']) == false) {
$username = 'failed';
$error = true;
}
if ( ! $error) {
//passed all basic validation
}
}
?>
<style type='text/css'>
.failed {
border: thin solid #e51923;
}
</style>
<form method="post">
<input type="text" name="email" class="<?php echo $email; ?>" /> <br />
<input type="text"name="name" class="<?php echo $name; ?>"/> <br />
<input type="text" name="message" class="<?php echo $message; ?>"/> <br />
<input type="text" name="pref-job" class="<?php echo $pref_job; ?>"/> <br />
<input type="text" name="username" class="<?php echo $username; ?>"/> <br />
<input type="submit" value="Submit"/>
</form>
Unless you want to allow empty space values

PHP Guessing Number

This is a random number guessing game between 1 and 100.
I am stuck on the guessing number part. The code doesn't work, whatever number I put it just show me the message "Your number is lower!".I need help.
This is what I have so far.
<?php
$x = rand(1, 100);
$num = '';
if (isset($_POST['submit'])) {
if ($num < $x)
{
echo " Your number is lower! <br />";
} elseif ($num > $x)
{
echo " Your number is higher! <br />";
} elseif ($num == $x)
{
echo " Congratulations! You guessed the hidden number. <br />";
} else
{
echo " You never set a number! <br />";
}
}
?>
<p>
<form action="" method="post">
<input type="text" name="num">
<button type="submit" name="submit">Guess</button>
<button type="reset" name="Reset">Reset</button>
</form>
</p>
You will always get lower because There isn't any value inside you $num.So, You need to assigning $num
<?php
$x = rand(1, 100);
$num = '';
if (isset($_POST['submit'])) {
$num = $_POST['num']; // Add this to set value for $num variable
if ($num < $x)
{
echo " Your number is lower! <br />";
} elseif ($num > $x)
{
echo " Your number is higher! <br />";
} elseif ($num == $x)
{
echo " Congratulations! You guessed the hidden number. <br />";
} else
{
echo " You never set a number! <br />";
}
}
?>
You need to set the num after submit the form.
if (isset($_POST['submit'])) {
$num = $_POST['num'];
if ($num < $x)
{
echo " Your number is lower! <br />";
} elseif ($num > $x)
{
echo " Your number is higher! <br />";
} elseif ($num == $x)
{
echo " Congratulations! You guessed the hidden number. <br />";
} else
{
echo " You never set a number! <br />";
}
}
// value of $x is in between 1 and 100 means greater than 0 and lesser than 101
$x = rand(1, 100);
// $num value is empty and while you attempt to compare with this this will converted to zero
$num = '';
// thus $num<$x always returns true, thats the mistake you need to assign the submitted value to the $num variable like
$num=$_POST['num'];
// put above line just before the if($num<$x)
This would be a lot easier if you had it as a switch/case statement:
$x = rand(1,1000);
if(isset($_POST['submit'])) {
$num = $_POST['num'];
switch($num) {
case ($num < $x):
echo " Your number is lower! <br />";
break;
case ($num > $x):
echo " Your number is higher! <br />";
break;
case ($num == $x):
echo " Congratulations! You guessed the hidden number. <br />";
break;
case '':
echo " You never set a number! <br />";
break;
}
}
Example/Demo
You have set $num = '' (a fix empty string) and compare it with a random generated number. It's obvious that this can not work. You have to read $_POST['num'] in PHP.
This will work, however, not as probably expected. You will need to either store the random number in a session or easier add a hidden field to the form. Otherwise the random number will change on each try.
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 ?>
<? php ?>
<?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; ?>
<? php ?>
that's all folks ...

PHP How to print selected answer in green

This is similar to a previous question I asked about matching the selected radio button with the value in the input field.
The code lets a user build a quiz by entering a question and 4 possible answers. You must select one of the answers as the correct one and on a separate PHP page, the answers must be displayed with the correct one in green. Originally this problem was solved, but after I modified the code for validation, the original loop for display would not work.
Here is the output of the code:
I need Albany to print in green since it's the correct answer and was selected with the radio button.
Here is my code for the form:
<?php
session_start();
// Define variables and set to empty values
$questionErr = $answer0Err = $answer1Err = $answer2Err = $answer3Err = "";
$question = $answer0 = $answer1 = $answer2 = $answer3 = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$valid = True;
if (empty($_POST['question'])) {
$questionErr = "Please supply a question";
$valid = False;
} else {
$question = test_input($_POST['question']);
$_SESSION['question'] = $_POST['question'];
}
if (empty($_POST['answer0'])) {
$answer0Err = "Please supply a possible answer";
$valid = False;
} else {
$answer0 = test_input($_POST['answer0']);
$_SESSION['answer0'] = $_POST['answer0'];
}
if (empty($_POST['answer1'])) {
$answer1Err = "Please supply a possible answer";
$valid = False;
} else {
$answer1 = test_input($_POST['answer1']);
$_SESSION['answer1'] = $_POST['answer1'];
}
if (empty($_POST['answer2'])) {
$answer2Err = "Please supply a possible answer";
$valid = False;
} else {
$answer2 = test_input($_POST['answer2']);
$_SESSION['answer2'] = $_POST['answer2'];
}
if (empty($_POST['answer3'])) {
$answer3Err = "Please supply a possible answer";
$valid = False;
} else {
$answer3 = test_input($_POST['answer3']);
$_SESSION['answer3'] = $_POST['answer3'];
}
}
// Function to sanitize data
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// If valid, send to QuestionReview.php to display answers
if ($valid) {
$_SESSION['radio'] = $_POST['radio'];
header('location: QuestionReview.php');
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>User-Created Quiz</title>
<style>
.shadow {
-webkit-box-shadow: 3px 3px 5px 6px #ccc; /* Safari 3-4, iOS 4.0.2 - 4.2, Android 2.3+ */
-moz-box-shadow: 3px 3px 5px 6px #ccc; /* Firefox 3.5 - 3.6 */
box-shadow: 3px 3px 5px 6px #ccc; /* Opera 10.5, IE 9, Firefox 4+, Chrome 6+, iOS 5 */
}
.instructions {
color: #696D6E;
}
#form-background {
background-color: #ECEDE8;
}
.error {
color: red;
}
</style>
</head>
<body>
<div style="width:600px">
<fieldset id="form-background" class="shadow">
<h1 class="instructions" style="text-align:center">User-Created Quiz</h1>
<p class="instructions" style="text-align:center">
<strong>Please enter a question of your own,
along with 4 possible answers in the
form below. Be sure to select the
correct answer to your question
before submitting the form.</strong>
</p>
<form style="text-align:center;" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<br>
<label class="instructions" for="question" >Enter your question here</label><br>
<input type="text" name="question" size="50" value='<?php echo $question;?>' />
<span class="error">* <br /><?php echo $questionErr; ?></span>
<br><br>
<p class="instructions">
Please provide four answers to your question and select the
correct one.
</p>
<input type="radio" name="radio" value="answer0">
<input type="text" name="answer0" value="<?php echo $answer0; ?>" style="width:400px">
<span class="error">* <br /><?php echo $answer0Err; ?></span>
<br><br>
<input type="radio" name="radio" value="answer1">
<input type="text" name="answer1" value="<?php echo $answer1; ?>" style="width:400px">
<span class="error">* <br /><?php echo $answer1Err; ?></span>
<br><br>
<input type="radio" name="radio" value="answer2">
<input type="text" name="answer2" value="<?php echo $answer2; ?>" style="width:400px">
<span class="error">* <br /><?php echo $answer2Err; ?></span>
<br><br>
<input type="radio" name="radio" value="answer3">
<input type="text" name="answer3" value="<?php echo $answer3; ?>" style="width:400px">
<span class="error">* <br /><?php echo $answer3Err; ?></span>
<br><br>
<input type="submit" value="Submit Entry">
</form>
</fieldset>
</div>
</body>
</html>
And here is my code for the result page:
<?php
session_start();
// Pull all variables from SESSION
$question = $_SESSION['question'];
$answer0 = $_SESSION['answer0'];
$answer1 = $_SESSION['answer1'];
$answer2 = $_SESSION['answer2'];
$answer3 = $_SESSION['answer3'];
$radio = $_SESSION['radio'];
$answerArray = array($answer0, $answer1, $answer2, $answer3);
shuffle($answerArray);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Entry Review</title>
<style>
.instructions {
color: #696D6E;
}
</style>
</head>
<body>
<h1 class="instructions">Entry Review</h1>
<p><em>You entered the following question:</em></p>
<p><strong><?php echo $question; ?></strong></p><br>
<p><em>These are the answers you provided:</em>
<p>
<strong>
<?php
if(isset($_SESSION['radio'])) {
$radio = $_SESSION['radio'];
foreach ($answerArray as $value) {
echo $value . "<br />";
}
} else {
echo "Please click the back button in your browser and select a correct answer";
}
?>
</strong>
</p>
</body>
</html>
Get a bit of A4 plain paper, work away from your computer for ten minutes.
Now, establish what you're trying to achieve in blocks, what do you want each part of your skillset/language/operator-syntax (PHP, javascript, CSS, HTML etc.) to do?
You have a list of outputs already displayed on your project and you want to mark a chosen output, as differet from the others.
work backwards from that end result, what will make this change? That's right, CSS, so you can write on your paper, you need a CSS class (or other identifier) for a chosen output, that you can call for that answer.
So how will the CSS know which output to choose? Where is this data held?
This data appears to be in PHP somewhere, (but it's not immediately obvious from your code). So, you need a PHP IF statement to check If the answer that is being displayed to the browser is the answer that the user has chosen then that answer needs to be encased in a CSS class somehow (<div> or <span> ) to effect the dfference in appearance.
And that's it. You should have enough of a structure now to go away and to write out notes on that A4 sheet and then use those notes to break your various issues down into component parts (here, there are parts for difining what behaviour should happen and then parts for making that behaviour happen).
Rewrite your code in 5-10 minutes you'll have it exactly as you want it.
On QuestionReview.php page, get the correct answer like this,
$correct_answer = $_SESSION[$_SESSION['radio']];
So keep your quiz page as it is and after submitting, process your form like this:
QuestionReview.php:
<?php
session_start();
// Pull all variables from SESSION
$question = $_SESSION['question'];
$answer0 = $_SESSION['answer0'];
$answer1 = $_SESSION['answer1'];
$answer2 = $_SESSION['answer2'];
$answer3 = $_SESSION['answer3'];
$correct_answer = $_SESSION[$_SESSION['radio']];
$answerArray = array($answer0, $answer1, $answer2, $answer3);
shuffle($answerArray);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Entry Review</title>
<style>
.instructions {
color: #696D6E;
}
</style>
</head>
<body>
<h1 class="instructions">Entry Review</h1>
<p><em>You entered the following question:</em></p>
<p><strong><?php echo $question; ?></strong></p><br>
<p><em>These are the answers you provided:</em>
<p>
<strong>
<?php
if(isset($_SESSION['radio'])) {
foreach ($answerArray as $value) {
$output = "<span";
if($value == $correct_answer){
$output .= " class='instructions'";
}
$output .= ">" . $value . "</span><br />";
echo $output;
}
} else {
echo "Please click the back button in your browser and select a correct answer";
}
?>
</strong>
</p>
</body>
</html>
In each iteration of the foreach loop, check if the current option equals to the correct answer or not. If it is then apply the class instructions to the current option.
Output: (Screenshot)
You are almost there... just make it simple:
If you have:
$question = $_SESSION['question'];
$radio = $_SESSION['radio'];
$answerArray = [$_SESSION['answer0'], $_SESSION['answer1'], $_SESSION['answer2'], $_SESSION['answer3']];
Then you can:
if(isset($_SESSION['radio'])) {
foreach ($answerArray as $value) {
echo $_SESSION['radio'] == $value ? "<span style=\"color:green\">Make $value green.</span><br />" : "<span style=\"color:#666\">Make $value grey or red.</span><br />";
}
} else {
echo "Please click the back button in your browser and select a correct answer";
}
Which equals to:
if(isset($_SESSION['radio'])) {
foreach ($answerArray as $value) {
if ($_SESSION['radio'] == $value){
echo "<span style=\"color:green\">Make $value green.</span><br />";
} else {
echo "<span style=\"color:#666\">Make $value grey or red.</span><br />";
}
}
} else {
echo "Please click the back button in your browser and select a correct answer";
}

(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