PHP Pythagoras check if it's the right answer - php

Hello i made this code below but i want it to be able to check if i guessed the answer good. If i insert 3 and 4 the answer is 5 but how do i let the code check if the answer "5" is right with the 2("3 and 4") input fields. So if all three input fields are correct. echo good and if not echo false. I am bad at explaining but i hope it's clear.
<form method="POST">
<label>Rechthoek verticaal</label>
<input name="vert"></input>
<label>Rechthoek horizontaal</label>
<input name="hor"></input>
<label>Schijne zijde</label>
<input name="schuin"></input>
<input type="submit" name="submit"></input>
</form>
<?php
if(isset($_POST['submit'])) {
$vert = $_POST['vert'];
$hor = $_POST['hor'];
$schuin = $_POST['schuin'];
$vert = pow($vert,2);
$hor = pow($hor,2);
$schuin = sqrt($vert + $hor);
echo $schuin;
}
?>

You need to check wheter sqrt($vert + $hor) is same as $_POST['schuin']
<form method="POST">
<label>Rechthoek verticaal</label>
<input name="vert"></input>
<label>Rechthoek horizontaal</label>
<input name="hor"></input>
<label>Schijne zijde</label>
<input name="schuin"></input>
<input type="submit" name="submit"></input>
</form>
<?php
if(isset($_POST['submit'])) {
$vert = $_POST['vert'];
$hor = $_POST['hor'];
$schuin = $_POST['schuin'];
$vert = pow($vert,2);
$hor = pow($hor,2);
if ($schuin == sqrt($vert + $hor)) {
echo "Good";
}
else {
echo "False";
echo "<br> Answer : ".sqrt($vert + $hor);
}

I'm not pretty sure to be understanding your problem, but if i'm, just compare the POST var with the calculated one:
echo ($schuin == $_POST['schuin'])?'good':'false';
PD: you are usingthe same var "$schuin" twice.

Related

"How to have the user add two random integers on a single page using $_POST"

I am trying to create an adding game PHP and HTML, where the user guesses the sum of two random integers. However, when the user submits the answer, the integers randomize again, changing the sum and making the user's guess incorrect.
<?php
$x = (rand(1,10));
$y = (rand(1,10));
$sum = $x + $y;
if (isset($_POST['submit']))
{
$guess = $_POST['guess'];
if ($sum == $guess)
{
echo "nice, you got it right.";
}
else {
echo "aw, too bad. <br>";
}
}
echo "<br>What is " . $x . " + " . $y . "? <br>";?>
<form action="" method="post">
<input name="guess" type="text" />
<input name="submit" type="submit" />
</form>
I am expecting the output to be "nice, you got it right" when the $guess==$sum, but $sum changes when the form is submitted, making the 2 variables unequal.
Try to use session and store the two random number. PHP Session
just like this.
<?php
session_start();
if (isset($_POST['submit']))
{
$sum = $_SESSION['y'] + $_SESSION['x'];
$guess = $_POST['guess'];
if ($sum == $guess)
{
echo "nice, you got it right.";
}
else {
echo "aw, too bad. <br>";
}
}
$_SESSION['x']= (rand(1,10));
$_SESSION['y']= (rand(1,10));
echo "<br>What is " . $_SESSION['x'] . " + " . $_SESSION['y'] . "? <br>";
?>
<form action="" method="post">
<input name="guess" type="text" />
<input name="submit" type="submit" />
</form>
I hope I answer your problem. just read the PHP session it helps you a lot.
You can create a hidden input field to post the sum value. Then compare that value with the guessed value.
<?php
$x = (rand(1,10));
$y = (rand(1,10));
$sum = $x + $y;
if (isset($_POST['submit'])) {
$guess = $_POST['guess'];
$value = $_POST['sum'];
if ($value == $guess) {
echo "nice, you got it right.";
} else {
echo "aw, too bad. <br>";
}
}
echo "<br>What is " . $x . " + " . $y . "? <br>";
?>
<form action="" method="post">
<input name="guess" type="text" />
<input type="hidden" name="sum" value="<?=$sum?>" />
<input name="submit" type="submit" />
</form>
You should store your $x and $y in a hidden input.
Calculate the sum by using the post value instead of generating new value.

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.

PHP Rand() resetting in maths game

I'm using PHP's Rand() function to generate two random numbers that I can compare against the user's, and echo out a success message if the user's answer equals (1st random number + 2nd random number.) However, I'm running into problems.
I suspected that the form was re-generating the numbers every time the form POSTED and the input was collected, so I tried using sessions instead to keep those numbers persistent. It's a mess to say the least.
I found this existing post: Problems with guess a number game , but the solution didn't remedy my problem.
<?php
if(empty($_POST))
{
$_SESSION['$number1'] = Rand(0, 100);
$_SESSION['$number2'] = Rand(0, 100);
}
if($_POST["submit"])
{
$input = $_POST['input'];
if($input == ($_SESSION['$number1'] + $_SESSION['$number2']))
{
echo "Correct! ";
}
else
{
echo "Incorrect! ";
}
}
echo "<hr><br> What is... <b>" . $_SESSION['$number1'] . " + " . $_SESSION['$number2'] . "</b>";
?>
<form action="" method="post">
<input type="text" name="input">
<input type="submit" name="submit">
</form>
<?php
echo "<b>DEBUG ANSWER: </b> " . ($_SESSION['$number1'] + $_SESSION['$number2']);
?>
Any help would be appreciated!
I changed a few things, personally, I wouldn't use the session, rather user hidden inputs. (if you're worried about security.. you shouldn't be.. numbers game, not banking site)
<?php
//Create a function to generate the random numbers (So we can re-use it)
function generateNumbers()
{
$one = Rand(0, 100);
$two = Rand(0, 100);
//Now return the random numbers
return array('number1' => $one, 'number2' => $two);
}
//Check if the submit button has been clicked
if($_POST["submit"])
{
$input = $_POST['input'];
if($input == $_POST['number1'] + $_POST['number2'])
{
echo "Correct! ";
}
else
{
echo "Incorrect! ";
}
}
//Now we create the numbers
$numbers = generateNumbers();
echo "<hr><br> What is... <b>" . $numbers['number1'] . " + " . $numbers['number2'] . "</b>";
?>
<form action="" method="post">
<input type="text" name="input">
<input type="submit" name="submit">
<!-- Personally I would rather use hidden inputs, than use the session -->
<input type="hidden" name="number1" value="<?php echo $numbers['number1'] ?>" />
<input type="hidden" name="number2" value="<?php echo $numbers['number2'] ?>" />
</form>
<?php
echo "<b>DEBUG ANSWER: </b> " . ($numbers['number1'] + $numbers['number2']);
?>

Wrong/right counter for user input evaluation PHP

I have built a simple calculator that uses random numbers and operations (+,-,*,/). Users can fill in a form for each question and their input is evaluated. However, instead of just displaying "That's right" or "That's wrong" for single questions, I want to show the accuracy/failure of their input over more questions (e.g. 50). Therefore, I am looking for a numerical counter, one that might just consist in a simple number that counts up everytime the user gives the correct answer (might be green), and a second one (red) that counts when the user gives a wrong answer. Both numbers should be displayed constantly. After 50 times, it would display the percentage of right answers.
Can I do this with sessions? And if so, how? Right now, the page is refreshing with every new click on the submit button. The more specific you can get the better since I am not an expert (yet). THANKS for any help!! Please finde my code below:
<div style="text-align: center; font-weight: bold; font-size: x-large">
<?php
$number1 = rand(1,100);
$number2 = rand(1,100);
$number3 = rand(1,20);
$number4 = rand(1,20);
switch(rand(0,3)) {
case 0:
$solution = $number1 + $number2;
echo "$number1+$number2=?";
break;
case 1:
$solution = $number1 - $number2;
echo "$number1-$number2=?";
break;
case 2:
$solution = $number3 * $number4;
echo "$number3*$number4=?";
break;
case 3:
$solution = $number3 / $number4;
echo "$number3/$number4=?";
break;
}
?>
<form action="form10.php" method="post">
Your Answer:<br>
<input type="integer" name="answer">
<input type="hidden" name="solution" value="<?php echo $solution; ?>">
<input type="Submit" value="Submit!">
</form>
<?php
if(isset($_POST['answer']) && isset($_POST['solution'])) {
if ($_POST["answer"] == round($_POST['solution'],1)) {
echo "<font color='#008000'> That's right! </font>";;
} else {
echo "That's wrong!";
}
}
?>
</div>
Looks like you just need a $counter value to persist...
<input type="hidden" name="counter" value="<?php echo $counter; ?>">
and then to increment...
if( isset($_POST['counter']) )
$counter= $_POST['counter'] + 1;
Example 'test.php' = keep clicking the Submit button...
<?php
$counter=0;
if( isset($_POST['counter']) )
$counter= $_POST['counter'] + 1;
?>
<form action="test.php" method="post">
Your Answer:<br>
<input type="integer" name="answer">
<input type="hidden" name="counter" value="<?php echo $counter; ?>">
<input type="Submit" value="Submit!">
<br>
Counter = <?php echo $counter; ?>
</form>

How to validate form input on the same page by using random numbers?

Would be awesome if you could help me out! I am trying to build a simple page to display random math questions. The answers should be typed in by the user and should be validated on the same page, giving him feedback on success and failure.
The problem is that by submitting the form input to the same page (I called it "form6.php") the page reloads and a new set of numbers is generated - that is why the "solution" variable is newly defined and cannot be used to test the accuracy of the user's answer.
This is the code I have so far (works fine for fixed numbers but fails with the random number generation):
<?php
$number1 = rand(1,100);
$number2 = rand(1,100);
$solution = $number1+$number2;
echo "$number1+$number2=?";
?>
<form action="form6.php" method="post">
Your Answer:<br>
<input type="integer" name="answer">
<input type="Submit" value="Submit!">
</form>
<?php
if(isset($_POST['answer'])){
if ($_POST["answer"] == $solution)
{echo "That's right";}
else
{echo "That's wrong!";};
}
?>
Any help is highly appreciated! Since I am not a professional coder, the more specific you can get, the better!
A POSTed form will reload your PHP script, causing 2 new rand() numbers to be generated. You're going to want to pass the solution in the form.
Edit: I updated the answer to show a quick solution for using random operands for verification. This was simply done by switching through a random integer. Please note that when using - or / you may receive non-integer numbers (3 / 58 or 15 - 86), so you may want to add some custom logic to prevent this.
<?php
$number1 = rand(1,100);
$number2 = rand(1,100);
switch(rand(0,3)) {
case 0:
$solution = $number1 + $number2;
echo "$number1+$number2=?";
break;
case 1:
$solution = $number1 - $number2;
echo "$number1-$number2=?";
break;
case 2:
$solution = $number1 * $number2;
echo "$number1*$number2=?";
break;
case 3:
$solution = $number1 / $number2;
echo "$number1/$number2=?";
break;
}
?>
<form action="form6.php" method="post">
Your Answer:<br><input type="integer" name="answer">
<input type="hidden" name="solution" value="<?php echo $solution; ?>">
<input type="Submit" value="Submit!">
</form>
<?php
if(isset($_POST['answer']) && isset($_POST['solution'])) {
if ($_POST["answer"] == $_POST['solution']) {
// Valid
} else {
// Incorrect
}
}
?>
If you don't want to include the solution in your form (be it hidden), you have to store solutions in a separate text file in which you can, for instance, serialize your data.
Alternatively, you can use sessions or cookies.
But you have to store the solution somewhere.
Here is an attempt with sessions:
<?php
session_start();
$nb1 = rand(1,100);
$nb2 = rand(1,100);
$_SESSION['number1'] = $nb1;
$_SESSION['number2'] = $nb2;
$_SESSION['solution'] = $nb1 + $nb2;
// (...)
if(isset($_POST['answer']))
{
if ($_POST["answer"] == $_SESSION['solution'])
{echo "That's right";}
else
{echo "That's wrong!";};
unset($_SESSION['nb1']);
unset($_SESSION['nb2']);
unset($_SESSION['nbsolution']);
}
if(isset($_POST['answer'])===true){
if ($_POST["answer"] == $solution)
{echo "That's right";}
else
{echo "That's wrong!";};
}
If you are using isset($_POST['answer']) you must include === true at the end
Also make sure you use instead of integer.
#user3261573,
As pointed out by #Sam, you could pass the value in a hidden field, but, as #Jivan said, a better approach would be using a session to store the solution.
Here's the code:
Ps.: I simplified the code for a better understanding.
<?php
// Initiate session
session_start();
// If the FORM has been submited, verify answer
if( isset($_SESSION['solution']) === TRUE && $_SESSION['solution'] !== NULL && isset($_POST['answer']) === TRUE && isset($_POST['solution']) == TRUE ){
if( $_SESSION['solution'] == $_POST['answer'] ){
echo 'That\'s right';
}else{
echo 'That\'s wrong';
}
}
// If the FORM ain't submited yet, display the question
else{
// Random numbers
$number1 = rand(1,100);
$number2 = rand(1,100);
// Store solution in session for further comparison
$_SESSION['solution'] = $number1+$number2;
// Echo question
echo "$number1+$number2=?";
echo '<form action="form6.php" method="post">
Your Answer:<br>
<input type="integer" name="answer">
<input type="Submit" value="Submit!">
</form>';
}
?>
If you like it, here's a few tutorials on using PHP SESSIONs:
http://www.w3schools.com/php/php_sessions.asp
http://www.php.net/manual/en/session.examples.basic.php
<?php
$number1 = rand(1,100);
$number2 = rand(1,100);
echo "$number1+$number2=?";
?>
<form action="form6.php" method="post">
Your Answer:<br>
<input type="integer" name="answer">
<input type="Submit" value="Submit!">
<input type="hidden" name="n1" value="$number1">
<input type="hidden" name="n2" value="$number2">
</form>
<?php
if(isset($_POST['answer'])){
$solution = $_POST['n1'] + $_POST['n2'];
if ($_POST["answer"] == $solution)
{echo "That's right";}
else
{echo "That's wrong!";};
}
?>

Categories