PHP random number not working - php

I want to write a php code that displays a random image and the person has to guess what it is. The problem is my php code tells me that the right city is incorrect, i cant figure out why
<?php
$random = rand(1, 3);
$answer ;
if ($random == 1) { $answer = "chicago" ;}
elseif($random == 2) {$answer = "LA" ;}
elseif($random == 3) {$answer = "NewYork" ;}
else {echo "Answer is None" ; }
if (isset($_POST["choice"])) {
$a = $_POST["choice"];
if($a ==$answer){
echo "<br> working <br>" ;
}else {echo "<br> Not Working <br>";}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>City Guess</title>
</head>
<body>
<center>
<img src="four/Image_<?php echo $random ;?>.jpg" width="960" height="639" alt=""/>
<form action="" method="POST">
chicago <input type= "radio" name="choice" value="chicago" />
<br>
LA <input type= "radio" name="choice" value="LA" />
<br>
NewYork <input type= "radio" name="choice" value="NewYork" />
<br>
<input type ="submit" value="Submit" />
</form>
</center>
</body>
</html>

You're generating your random value EVERYTIME the page is loaded. e.g. when the person first visits it and gets the form, you generate 2. When the form is submitted, you generate ANOTHER value, and this time it's 3. So even though the user correctly answers 2, you say they're wrong because the you've forgotten what you originally asked.
You need to store the generated value somehow, and compare that to the response, e.g.
$rand = rand(1,3);
<input type="hidden" name="correct_answer" value="$rand">
if ($_SERVER["REQUEST_METHOD"] == 'POST') {
if ($_POST['correct_answer'] == $_POST['user_answer']) {
echo 'correct';
}
}

The problem is your logic, you do not store the generated number that is used to show the image, instead you generate a new number every time you open the page.
You should store the generated number in (for example...) a session to preserve it and use that to compare.

Try it:
$random = floor(rand(1, 4));
I hope it helps.

Add the following hidden field in your form, using value="<?php echo $answer ?>" and it will work with your present code.
<input type="hidden" name="correct_answer" value="<?php echo $answer ?>">
Matter 'o fact, you don't even need name="correct_answer"
Just do:
<input type="hidden" value="<?php echo $answer ?>">
Remember when you test this, you have a "1 in 3" chance for success!
Edit
Here's the code that I used:
<?php
$random = rand(1, 3);
$answer;
if ($random == 1) { $answer = "chicago" ;}
elseif($random == 2) {$answer = "LA" ;}
elseif($random == 3) {$answer = "NewYork" ;}
else {echo "Answer is None" ; }
if (isset($_POST["choice"])) {
$a = $_POST["choice"];
if($a ==$answer){
echo "<br> working <br>" ;
}else {echo "<br> Not Working <br>";}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>City Guess</title>
</head>
<body>
<center>
<img src="four/Image_<?php echo $random ;?>.jpg" width="960" height="639" alt=""/>
<form action="" method="POST">
<input type="hidden" value="<?php echo $answer ?>">
chicago <input type= "radio" name="choice" value="chicago" />
<br>
LA <input type= "radio" name="choice" value="LA" />
<br>
NewYork <input type= "radio" name="choice" value="NewYork" />
<br>
<input type ="submit" value="Submit" />
</form>
</center>
</body>
</html>

Related

2 checkboxes for ball's area and circumference

I have an html file with form with 2 checboxes in it, and I wanted to calculate the area and circumference of ball, but the form doesn't return any value...
HTML file:
<!DOCTYPE html>
<html>
<head>
<title>Ball</title>
<meta charset="UTF-8">
</head>
<body>
<form action="test.php" method="post">
Enter radius: <br><br>
<input type="text" name="radius"> <br><br>
Area:
<input type="checkbox" name="check_list[]" value="value 1"><br>
Circumference:
<input type="checkbox" name="check_list[]" value="value 2"><br>
<button type="submit">Calculate</button>
</form>
</body>
</html>
And the PHP file (I used foreach loop):
<?php
$radius = $_POST['radius'];
if(!empty($_POST['check_list'])) {
foreach($_POST['check_list'] as $check) {
if ($check == "0")
{
$result1 = 4*3.14*($radius*$radius);
echo "Area: " . $result1."<br>";
}
if ($check == "1")
{
$result2 = 4/3*3.14*($radius*$radius*$radius);
echo "Circumference: " . $result2 . "<br>";
}
}
?>
Why it doesn't work? What am I doing wrong?
Your current values of area and circumference check boxes are "value 1" and "value 2". Those are the values you get in the php code.
So in the if condition check for those values. i.e if($check=="value 1") or if($check ==" value 2").
But a better practice is to change the value check boxes to just "0" and "1".
It will be more easier.
Change the values of the checkbox items to value="0" for the area and value="1" for the Circumference
Then change the condition on your loop:
foreach($_POST['check_list'] as $option => $check)

How do I make my radio buttons work with if statements for calculations?

so for a class assignment we are using HTML and PHP to make a form that asks a user to input two (2) numbers and to choose between addition, subtraction, multiplication or division form using radio buttons, THEN to input a guess as to what the answer is. Our assignment is to echo out to the user specifying whether or not their answer is correct or not.
The part where I am having troubles is in the "if" and "else" statements. For example, if I choose 1 and 2 as my numbers, guess 3 and choose addition as my method of calculation, I not only get echoed out "Congratulations! You choose the correct answer of 3!" but i also get my else statements from division, subtraction, and multiplication specifying that I did it incorrectly.
Here's my Code:(keep in mind-- the birthday function has yet to be made.)
Also, I'm having difficulties regarding my form validation -- making it so that the user has in fact entered the required fields.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Howdy</title>
</head>
<body>
<h1>PHP_SELF</h1>
<?php
//process the form if the submit button was pressed
if (isset($_POST['submit'])) {
//form validation goes here
/////////////////////////////////////////VARIABLES ARE BEING MADE HERE
//simplify the form variables
//later on we will do this in form validation
//create a variable called firstname and store in it
//the value from the POST array for firstname from the form
$firstname = $_POST['firstname'];
//creating variables for num1 and num2 that user inputed
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
//creating a variable called sum
//this is for when the user chooses to ADD
//num1 and num2
$sum = $num1 + $num2;
//creating a variable called difference
//this is for when the user chooses to SUBTRACT
//num1 and num2
$difference = $num1 - $num2;
//creating a variable called product
//this is for when the user chooses to MULTIPLY
//num1 and num2
$product = $num1 * $num2;
//creating a variable called quotient
//this is for when the user chooses to DIVIDE
//num1 and num2
$quotient = $num1 / $num2;
//creating a variable called guess and store it in the
//value from the POST array for the guess from the form
$guess = $_POST['guess'];
//creating a variable called birthday and store it in the
//value from the POST array for the user's birthday
$birthday = $_POST['birthday'];
if ($sum == $guess) {
echo "<p>Congratulations $firstname. You answered correctly with $guess.<p>\n";
} else if ($sum != $guess){
echo "<p>$firstname, you answered incorrectly. The correct answer is $sum.</p>\n";
}
if ($difference == $guess) {
echo "<p>Congratulations $firstname. You answered correctly with $guess.<p>\n";
} else if ($difference != $guess){
echo "<p>$firstname, you answered incorrectly. The correct answer is $difference.</p>\n";
}
if ($product == $guess) {
echo "<p>Congratulations $firstname. You answered correctly with $guess.<p>\n";
} else if ($product != $guess){
echo "<p>$firstname, you answered incorrectly. The correct answer is $product.</p>\n";
}
if ($quotient == $guess) {
echo "<p>Congratulations $firstname. You answered correctly with $guess.<p>\n";
} else if ($quotient != $guess){
echo "<p>$firstname, you answered incorrectly. The correct answer is $quotient.</p>\n";
}
} //end of the isset submit conditional statement
//show the form if it is the user's first time her OR if any of the required forms are missing
if(!isset($_POST ['submit']) OR empty($firstname) OR empty($num1) OR empty($num2)) { ?>
<h2>Please fill out the following: </h2>
<!--FORM BEGINS-->
<form action= "<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p><label for="firstname">Please enter your first name: </label>
<input id="firstname" type="text" size="30" name="firstname" value="<?php if(isset($firstname)) echo $firstname; ?>"/><p>
<!--Challenge Dealio-->
<p><label for="Num1">Please enter a number: </label>
<input id="Num1" type="number" size="30" name="num1" value="<?php if(isset($num1)) echo $num1; ?>" /></p>
<p><label for="Num2">Please enter another number: </label>
<input id="Num2" type="number" size="30" name="num2" value="<?php if(isset($num2)) echo $num2; ?>"/><p>
<p>Please choose one of the following: </p>
<p>
<input name="add" id="answer" type="radio" value="add" />Add<br />
<input name="subtract" id="answer" type="radio" value="subtract" />Subtract<br />
<input name="multiply" id="answer" type="radio" value="multiply" />Multiply<br />
<input name="divide" id="answer" type="radio" value="divide" />Divide<br />
</p>
<p><label for="guess">Please put in a guess for the answer: </label>
<input id="guess" type="number" size="30" name="guess" value="<?php if(isset($guess)) echo $guess; ?>"/></p>
<p><label for="birthday">Please enter your birth date: </label>
<input id="birthday" type="date" size="30" name="birthday" value="<?php if(isset($birthday)) echo $birthday; ?>"/></p>
<!--Submit Button-->
<input type="submit" name="submit" value="Enter" />
</form>
<?php
} //end form conditional statement
?>
</body>
</html>
What did I do wrong? And how can I go about fixing this?
First of all al radio buttons should have same name with different value. And in same page you cannot have same id's
<p>
<input name="action" id="add" type="radio" value="add" />Add<br />
<input name="action" id="subtract" type="radio" value="subtract" />Subtract<br />
<input name="action" id="multiply" type="radio" value="multiply" />Multiply<br />
<input name="action" id="divide" type="radio" value="divide" />Divide<br />
</p>
Then in your php to perform selected option,
if($_POST['action'] == "add") {
$result = $num1 + $num2;
} else if($_POST['action'] == "subtract") {
$result = $num1 - $num2;
} else if($_POST['action'] == "multiply") {
$result = $num1 * $num2;
} else if($_POST['action'] == "divide") {
$result = $num1 / $num2;
}
Rename all values to $result.
if($result == $guess) {
echo "<p>Congratulations $firstname. You answered correctly with $guess.<p>\n";
} else {
echo "<p>$firstname, you answered incorrectly. The correct answer is $difference.</p>\n";
}
No need to check so many times, take the result to 1 variable, check it only once.
Edit: For birthday part
In View
<select name="year">add options here</select>
<select name="month">add options here</select>
<select name="day">add options here</select>
In PHP,
$month = $_POST['month'];
$year = $_POST['year'];
$day = $_POST['day'];
$date = $year ."-". $month ."-".$day;
$date = date("Y-m-d",strtotime($date));
if(date('m-d') == date('m-d', $date)) {
// today is users birthday. show any message you want here.
}
First of all you cannot have the same ids on your radios. They must be different with the same name.
<p>
<input name="action" id="add" type="radio" value="add" />Add<br />
<input name="action" id="subtract" type="radio" value="subtract" />Subtract<br />
<input name="action" id="multiply" type="radio" value="multiply" />Multiply<br />
<input name="action" id="divide" type="radio" value="divide" />Divide<br />
</p>
Then you are not validating which function the user is choosing via the checkboxes. You are iterating through all the ifand elsewithout filtering which function was chosen.
What I would do is use a Switch Case statement to filter which method of calculation was chosen and then compare if the guess is right. Something like:
switch $answer {
case "add":
//Check if guess is right and echo
break;
case "substract":
//Check if guess is right and echo
break;
case "multiply":
//Check if guess is right and echo
break;
case "divide":
//Check if guess is right and echo
break;
};
If you are not allowed to use the Switch Case Statement then you should first check which answer was marked and then if the guess is right:
if($answer == "add"){
if($sum == $guess){
echo "Congrats";
} else {
echo "error";
}
} else if($answer == "substract"){
if($difference == $guess){
echo "Congrats";
} else {
echo "error";
}
} else if($answer == "multiply"){
if($product == $guess){
echo "Congrats";
} else {
echo "error";
}
} else if($answer == "divide"){
if($quotient == $guess){
echo "Congrats";
} else {
echo "error";
}
}
Hope it helps.

my other if else statement is executing php

I have 3 forms with 3 radios each but executed one at a time because of random generator. If I click a radio, it will go to next page and will be checked by the if else statement. Now my problem is, when it gets answered and it's correct, it will output yes. However, my other if else statement of my other radio executes. Since it's not answered, it assumed that it was wrong, so it outputted no.
here's my code:
<!doctype html>
<html>
<head>
<title>Question and Answer</title>
</head>
<body>
<?php
//Creating random numbers
$rid = rand(1,3);
?>
<?php
if ($rid == 1){
echo "
<form action='answer.php?id=1' method='post' id='quizForm' id='1'>
<ol>
<li>
<h3>What does HTML Stands For ?</h3>
<div>
<input type='radio' name='answerOne' id='answerOne' value='A' />
<label for='answerOneA'>A) Hyper text markup language</label>
</div>
<div>
<input type='radio' name='answerOne' id='answerOne' value='B' />
<label for='answerOneB'>B) Hyper turn mark lingo</label>
</div>
<div>
<input type='radio' name='answerOne' id='answerOne' value='C' />
<label for='answerOneC'>C) Happy tissue mahatma life</label>
</div>
</li>
<input type = 'submit' name = 'submit1' value = 'Choose..'>
</form>";
}
if ($rid == 2){
echo "
<form action='answer.php?id=1' method='post' id='quizForm' id='1'>
<ol>
<li>
<h3>What does CSS Stands For ?</h3>
<div>
<input type='radio' name='answer2' id='answer2' value='A' />
<label for='answer2A'>A) College Computer Studies</label>
</div>
<div>
<input type='radio' name='answer2' id='answer2' value='B' />
<label for='answer2B'>B) Cascading Style Sheet</label>
</div>
<div>
<input type='radio' name='answer2' id='answer2' value='C' />
<label for='answer2C'>C) Cascaded Style Sheet</label>
</div>
</li>
<input type = 'submit' name = 'submit1' value = 'Choose..'>
</form>";
}
if ($rid == 3){
echo "
<form action='answer.php?id=1' method='post' id='quizForm' id='1'>
<ol>
<li>
<h3>What does PHP Stands For ?</h3>
<div>
<input type='radio' name='answer3' id='answer3' value='A' />
<label for='answerOneA'>A) Hyper text markup language</label>
</div>
<div>
<input type='radio' name='answer3' id='answer3' value='B' />
<label for='answerOneB'>B) Hyper turn mark lingo</label>
</div>
<div>
<input type='radio' name='answer3' id='answer3' value='C' />
<label for='answerOneC'>C) Happy tissue mahatma life</label>
</div>
</li>
<input type = 'submit' name = 'submit1' value = 'Choose'>
</form>";
}
?>
</body>
</html>
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
<!doctype html>
<html>
<head>
<title>Question and Answer</title>
</head>
<body>
<?php
error_reporting(E_ALL ^ E_NOTICE);
$answer = array('A','B','C');
$answer1= $_POST['answerOne'];
$answer2= $_POST['answer2'];
if($answer1 == $answer[0]){
echo 'yes';
}
else if ($answer1 != $answer[0]){
echo 'no';
}
else{
}
if($answer2 == $answer[1]){
echo 'yes';
}
else if ($answer2 != $answer[1]){
echo 'no';
}
?>
</body>
</html>
Here is a cleaner way to do it. Inside is_correct function, it check if particular answer exist in $_POST, if so it returns if the answer is correct:
function is_correct()
{
$answer = array(
'answerOne' => 'A',
'answer2' => 'B',
'answer3' => 'C',
);
foreach ($answer as $k => $v) {
if (array_key_exists($k, $_POST)) {
return $v == $_POST[$k];
}
}
return false;
}
if (is_correct()) {
echo "yes";
} else {
echo "no";
}

Using Session Tracking for Multipage Form in PHP

I'm trying to display a multiple page form that preserves submitted data from one page to the next using session tracking. $_POST['stage'] determines which form should be displayed. Each form has a hidden input type with a value set to increment the $stage variable by 1 but when I submit the data from the first form, the value of $stage seems to remain the same as I don't see the next form. Sessions is enabled in php.ini.
Here's my example:
<?php
session_start();
//Determine which integer to assign to the stage
if (($_SERVER['REQUEST_METHOD'] == 'GET') || (!isset($_POST['stage']))) {
$stage = 1;
} else {
$stage = (int) $_POST['stage'];
}
//Save any submitted data
if ($stage > 1) {
foreach ($_POST as $key => $value) {
$_SESSION[$key] = $value;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>My Form Example</title>
</head>
<body>
<?php if ($stage == 1) { ?>
<form action='<?php echo $_SERVER['SCRIPT_NAME'] ?>' method='post'>
<label for='firstField'>First field:</label>
<input type='text' name='first_field /><br />
<input type='hidden' name='stage' value='<?php echo $stage + 1 ?>' />
<input type='submit' value='Next' />
</form>
<?php } else if ($stage == 2) { ?>
<form action='<?php echo $_SERVER['SCRIPT_NAME'] ?>' method='post'>
<label for='secondField'>Second field:</label>
<input type='text' name='second_field /<br />
<input type='hidden' name='stage' value='<?php echo $stage + 1 ?>' />
<input type='hidden' value='Done' />
</form>
<?php } ?>
</body>
</html>
Try adding session_start() at the top of your page. That's the first thing I've noticed.
I discovered a typo on my working script. Hindsight, I should have copied and pasted my entire script. Sorry. This script works fine (with session_start() at the beginning which still doesn't appear after I post the question).
Since you didn't mention what a problem is, which made me to sift and find exactly, I will put more precise answer. The problem is no ending single quote in the lines
<input type='text' name='first_field /><br />
and
<input type='text' name='second_field /<br />
and so my final working script is
<?php
session_start();
$stage = 0;
//Determine which integer to assign to the stage
if (!isset($_POST['stage'])) {
$stage = 1;
} else {
$stage = (int) $_POST['stage'];
}
//Save any submitted data
if ($stage > 1) {
foreach ($_POST as $key => $value) {
$_SESSION[$key] = $value;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>My Form Example</title>
</head>
<body>
<?php if ($stage == 1) { ?>
<form action='<?php echo $_SERVER['SCRIPT_NAME'] ?>' method='post'>
<label for='firstField'>First field:</label>
<input type='text' name='first_field' /><br />
<input type='hidden' name='stage' value='<?php echo $stage + 1 ?>' />
<input type='submit' value='Next' />
</form>
<?php } else if ($stage == 2) { ?>
<form action='<?php echo $_SERVER['SCRIPT_NAME'] ?>' method='post'>
<label for='secondField'>Second field:</label>
<input type='text' name='second_field' /<br />
<input type='hidden' name='stage' value='<?php echo $stage + 1 ?>' />
<input type='hidden' value='Done' />
</form>
<?php } ?>
</body>
</html>

In PHP how to output the contents of a radiobox array using POST?

I want to output the values of the checkbox in the same way I'm outputting the values from the text fields. Since the checkbox can have multiple inputs I'm using an array for that but trying to cycle through the array for values hasn't worked for me.
tried foreach($type as $item) and echoing $item within the HTML like it says in the PHP book I have but that hasn't worked.
How should I do and where should the code be? I'm also unable to use PHP within the HTML for some reason, I'm not sure why that is or if its something to do with the echo<<<_END or not. Help appreciated.
<?php // formtest.php
if (isset($_POST['game'])) $game = $_POST['game'];
else $game = "(Not entered)";
if (isset($_POST['genre'])) $genre = $_POST['genre'];
else $genre = "(Not entered)";
if (isset($_POST['type'])) $type = $_POST['type'];
else $type = "(Not entered)";
echo <<<_END
<html>
<head>
<title>Form Test</title>
</head>
<body>
Your game is: $game in the $genre genre and of the type<br />
<form method="post" action="formtest.php">
What is your game?
<input type="text" name="game" />
<br />
What is your genre?
<input type="text" name="genre" />
<br />
Type?
Retail <input type="checkbox" name="type[]" value="Retail" />
Downloadable <input type="checkbox" name="type[]" value="Downloadable" />
Free <input type="checkbox" name="type[]" value="Free" />
<br />
<input type="submit" />
</form>
</body>
</html>
_END;
?>
With the form as it is now, $_POST['type'] will be an array since it's using checkboxes (and named appropriately), not radios. Here I just implode it for display, but you can loop through it like any array. It should be worth noting that any time you're wondering what a form is giving you, you can var_dump($_POST) or var_dump($_GET) depending on where the data is coming from. It helps a lot with debugging.
Here's what I got, I switched from heredoc, but your heredoc should work fine if you add $type back in somewhere, I didn't notice it in the original code:
<?php // formtest.php
if (isset($_POST['game'])) $game = $_POST['game'];
else $game = "(Not entered)";
if (isset($_POST['genre'])) $genre = $_POST['genre']; //Edit: Fixed line, oops
else $genre = "(Not entered)";
if (isset($_POST['type'])) $type = implode(', ',$_POST['type']);
else $type = "(Not entered)";
//Normally I'd specify a charset, but for simplicity's sake I won't here.
$type = htmlspecialchars($type);
$game = htmlspecialchars($game);
$genre = htmlspecialchars($genre);
?>
<html>
<head>
<title>Form Test</title>
</head>
<body>
Your game is: <?php echo $game; ?> in
the <?php echo $genre; ?> genre and of the type <?php echo $type; ?><br />
<form method="post" action="">
What is your game?
<input type="text" name="game" />
<br />
What is your genre?
<input type="text" name="genre" />
<br />
Type?
Retail <input type="checkbox" name="type[]" value="Retail" />
Downloadable <input type="checkbox" name="type[]" value="Downloadable" />
Free <input type="checkbox" name="type[]" value="Free" />
<br />
<input type="submit" />
</form>
</body>
</html>
Addendum:
If you switched and used radios like
<input type="radio" name="type" value="Downloadable" />
$_POST['type'] would be a simple string since you can only select one of the set.
To the file you post it the type[] will be saved as an array. For example
$a=$_POST['type'];
Although I don't find any point in doing this to radio-buttons, because their purpose is to pass only 1 value(unless you want specifically to).
Ok, first you don't need to echo the entire html output. Second your questions says radio buttons, but the html shows checkboxes. A radio field will only produce one result so you don't need [] after then name. Checkboxes will return an array when named with a []. So if you are using checkboxes you will need to process the result as an array. If you change the field to radio it should work fine.
<?php // formtest.php
if (isset($_POST['game'])) {
$game = $_POST['game'];
}
else { $game = "(Not entered)"; }
if (isset($_POST['genre'])) {
$genre = $_POST['genre'];
}
else { $genre = "(Not entered)"; }
if (isset($_POST['type'])) {
$type = $_POST['type'];
}
else { $type = "(Not entered)"; }
?>
<html>
<head>
<title>Form Test</title>
</head>
<body>
Your game is: <?php echo $game; ?> in the <?php echo $genre; ?> genre and of the type <?php echo $type; ?><br />
<form method="post" action="test.php">
What is your game?
<input type="text" name="game" <?php if ($game != "(Not entered)") { echo "value='" . $game . "'"; } ?> />
<br />
What is your genre?
<input type="text" name="genre" <?php if ($genre != "(Not entered)") { echo "value='" . $genre . "'"; } ?> />
<br />
Type?
Retail <input type="radio" name="type" value="Retail" <?php if ($type == "Retail") { echo "checked"; } ?> />
Downloadable <input type="radio" name="type" value="Downloadable" <?php if ($type == "Downloadable") { echo "checked"; } ?> />
Free <input type="radio" name="type" value="Free" <?php if ($type == "Free") { echo "checked"; } ?> />
<br />
<input type="submit" />
</form>
</body>
</html>

Categories