I'm a new coder and I'm trying to write some code for a simple math game where you have to give the value of the second int in order to get to the sum.
I have it so the user submits their answer through a form and I want to have it so it checks the answer and if it is wrong it will display the correct answer. The issue I'm having is that after the user answers the question a new one is loaded and the code is checking the answer for the new question instead of the old one, displaying the answer to the new question.
For example, if the sum of int 1 and int 2 is 30 and the value of int 1 is 20, the value of int 2 must be 10 which is what the user would submit into the form.
I want to have it display "correct" or, if the user got it wrong, then "the correct answer is 10" but this is not the case because after the user answers the question it checks the answer for the new generated question and ends up displaying "the correct answer is 20" or whatever the new value of int 2 is. I do not know how to have it evaluate the answer for the old question as the variables are overwritten with the new question.
<?php
echo "<h2 id='heading'>php program to add two numbers...</h2><br />";
$val1 = rand(1, 100);
$val2 = rand(1, 100);
$sum = $val1 + $val2; /* Assignment operator */
echo "Result(SUM): $sum";
echo "<img src='math.jpg' alt='math' height='200' width='200'>";
echo "<h2>If val1 : $val1, what is val2</h2>";
echo "<form method = 'post'><input type='text' id='val2' name='val2' onChange='preventDefault();validateForm();'></form>";
if (strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
echo ('The Value You Choose Was: ' . $_POST['val2'] . '<br/>');
$_SESSION['value2'] = $val2;
if ($_POST['val2'] == $val2 && isset($_POST['val2'])) {
echo 'You Answered Correctly';
} elseif(isset($_POST['val2'])) {
echo ('Wrong the correct answer was: ' . $_SESSION['value2']);
}
}
?>
The problem is that you are regenerating $val1 and $val2 again before checking their response.
Lets say, on the first page load $val1 = 1 and $val2 = 2.
The screens should say something akin to 1 + ? = 3.
The user (correctly) answers 2 and submits the form. PHP starts from square one every time you run the script - so the first thing it'll do is generate $val1 = 5 and $val2 = 3. This has changed the answer. It is no longer correct.
So basically you need to save $val1 and $sum in your form (possibly as hidden fields) so that you can reference them when checking the answers. When the REQUEST_METHOD is POST - read from those instead of generating new ones.
As you might already imagine, your program needs to remember the values of the random numbers between the two requests. To achieve this, you can use session varibales. A session variable can be accessed during multiple requests, until the session expires.
http://php.net/manual/en/session.examples.basic.php
You already assing the result of your game to a session variable:
$_SESSION['value2'] = $val2;
But thats not enough:
start the session with session_start();
in your if comparison, use the session variable (so you compare to the value of the previous request) instead of the newly created value
assign the session variable after your if comparison (otherwise the session variable would have the new random nubmer instead of the previous one)
Final code (untested):
<?php
session_start();
echo "<h2 id='heading'>php program to add two numbers...</h2><br />";
$val1 = rand(1, 100);
$val2 = rand(1, 100);
$sum = $val1 + $val2; /* Assignment operator */
echo "Result(SUM): $sum";
echo "<img src='math.jpg' alt='math' height='200' width='200'>";
echo "<h2>If val1 : $val1, what is val2</h2>";
echo "<form method = 'post'><input type='text' id='val2' name='val2' onChange='preventDefault();validateForm();'></form>";
if (strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
echo ('The Value You Choose Was: ' . $_POST['val2'] . '<br/>');
if (isset($_POST['val2']) && $_POST['val2'] == $_SESSION['value2']) {
echo 'You Answered Correctly';
} elseif(isset($_POST['val2'])) {
echo ('Wrong the correct answer was: ' . $_SESSION['value2']);
}
}
$_SESSION['value2'] = $val2;
Related
I have a form sender which is posting a value of 6 to another form receiver. What I'm trying to achieve is store the posted value from sender into a variable in the receiverthen increment the variable it every time the sender posts. Then print the updated variable
This is what I have tried to do
$val= $_POST['val'];
$limit = 6 + $val;
echo $limit;
Im getting the result as 12. But what I want is
After first post result = 12
After second post result = 18
On and on...
NB:$_POST['val'] = 6;
session_start();
$limit = 6;
if(!isset($_SESSION['lastLimit'])) {
$_SESSION['lastLimit'] = 0;
}
if(!empty($_POST)) {
$_SESSION['lastLimit'] = $_SESSION['lastLimit'] + $limit;
$postedValue = $_POST['val'] + $_SESSION['lastLimit'];
echo $postedValue;
}
Because the web is stateless i.e. scripts do not remember anything that happened the last time a page/form was executed the receiver script does not remember anything from the last time it was run.
But dont panic, there is a way. Its called a SESSION and you can store data in the session which will then be available the next time this user connects to your site. In PHP you use it like this. The session is linked to this specific connection to a specific user.
receiver.php
<?php
// must be run at top of script, before any output is sent to the new form
session_start();
// did the form get posted and is the variable present
// or replace POST with GET if you are using an anchor to run the script
if ( $_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['val']) {
if ( isset($_SESSION['limit'] ){
// increment the limit
$_SESSION['limit'] += (int)$_POST['val'];
} else {
// initialize the limit
$_SESSION['limit'] = (int)$_POST['val'];
}
echo 'Current value of limit is = ' $_SESSION['limit'];
} else {
// something is not right
// direct this user to some basic page like the homepage or a login
header('Location: index.php');
}
You need an intermediate layer to store the value.
Available options:
1) Global static value
2) session
3) file
4) database
I would recommend global value or session, as they data you want to store isn't that huge and would meet the requirements easily.
I would not write the syntax to store it in session as a number of people have already mentioned it. I just wanted to clarify the problem scenario and possible solutions.
You can store $limti into global varibale .
global $val;
$val += $_POST['val'];
$limit = 6 + $val;
echo $limit;
Pretty sure this is a quick and easy question but I have a form that on action POST goes to a confirmation page. I need a message to display on the confirmation page if the user selects county1 but if user selects county2, county3, or county4. However, when I setup the statement it's not working. Probably a syntax error or two on my part. Any help would be greatly appreciated.
A messy idea of what I think should work:
<?php $county=$_POST['County'];
if ($county="Polk") {
echo "Important message about your county"; }
else {
echo " "; // Or nothing at all
}
?>
But
<?php echo $_POST['County'] ?>
displays the name of the county so I know the submission is carrying through. Thoughts on why my above code wouldn't be working? If you could flag syntax errors or code placement that'd be much appreciated! Thank you!
Inside the if condition you should use two equal operators instead of one . try this code
<?php
$county = isset($_POST['County'])?$_POST['County']:"";
if ($county == "Polk") {
echo "Important message about your county";
}
else {
echo " "; // Or nothing at all
}
?>
Use double equal in your if statement for comparison
See the answer and read the comment to understand why you have to change it
if ($county="Polk") {
Single equal is assignment operator, it assign value
Change this line to this
if ($county=="Polk") {
So your whole code should look like this
$county=$_POST['County'];
if ($county == "Polk") {
echo "Important message about your county";
}
else {
echo " "; // Or nothing at all
}
Use double equal sign, double equal is comparison operator,
Here you are checking if the $county is equal to Polk or not,
Means you are comparing value
I have a basic math question that the user has to answer before they can send an email:
$first_num = rand(1, 4);
$second_num = rand(1, 4);
$send = #$_POST['send'];
if($send){
//The user's answer from the input box
$answer = #$_POST["answer"];
if($answer == $first_num + $second_num) {
//Do stuff
}
else {
$error_message = "You answered the question wrong!";
}
}
I answer the question correctly (unless my first grade math is off!) yet it says I have the question wrong. I am not sure what the issue is but I imagine it is something to do with the fact that php executes immediately when the page is loaded and so new numbers are generated as soon as the user presses the submit button? Or am I way off? If that is the case, what can be done to solve this?
The problem is that you are setting your values every time your script is called. So when you post your form, two new values are set and they are likely not the same values as when you called the script the first time to show the form.
You should store your variables in a session and retrieve these values when you process your post request.
Something like:
session_start();
if (!isset($_SESSION['numbers']))
{
$_SESSION['numbers']['first'] = rand(1, 4);
$_SESSION['numbers']['second'] = rand(1, 4);
}
...
if ($answer == $_SESSION['numbers']['first'] + $_SESSION['numbers']['second']) {
//Do stuff
/**
unset the variables after successfully processing the form so that
you will get new ones next time you open the form
*/
unset($_SESSION['numbers']);
...
Note that you will need to use the session variables everywhere where you are using your own variables right now.
You should include the two numbers as hidden form inputs in your HTML, and then do the math with the entries in your $_POST array.
Make your code start like this instead:
$first_num = $_POST["first_num"];
$second_num = $_POST["second_num"];
This is what I have.
<?php
if (isset($_GET["var"])) {
echo "1";
} else {
echo "1";
}?>
I want it to check if there's been a variable set for "var" and if there isn't (which will happen the first time anyone goes to site), I want it to be set to "1". Then I want to create buttons "back" and "forward" that will will increase "var" by "1" until it reaches my limit of "10" then returns to one.
I can figure out the math and buttons part, I just need help initially setting "var" since it isn't already set when you go to the page.
Aside from architecture, security and any other issues:
$_GET is just a simple array accessible from anywhere in script.
$_GET['var'] = 'foo';
Docs: http://www.php.net/manual/en/language.variables.superglobals.php
Try this tag
<a her="www.example.com?var=<?php echo $get_var?>">your site name</a>
the get variables come in to the script like so
scriptname.php?getvar=val
To "set" the variable you would need to test for it, Increment it and redirect too it
$var = 1;
if (isset($_GET['var'])){
$var = (int) ($_GET['var'] +1);
if($var > 10) {
$var =1;
}
}
header("Location: " . $_SERVER['PHP_SELF'] ."?var=" . $var);
as mentioned in the comments, SESSION is a much better place to store this information
I've been learning PHP in my spare time, and this is one of my "Hello, World" type scripts I'm doing for practice.
This is the code below, and the default strings will not change so the code will end up looping into eternity for I have no idea why:
<?php
if (isset($_POST["pbankroll"], $_POST["pstartbet"]))
{
$bankroll = $_POST["pbankroll"];
$startBet = $_POST["pstartBet"];
//If using this code below instead of that above, everything will work fine:
//$bankroll = 200;
//$startBet = 25;
while($bankroll >= $startBet)
{
$evenOrOdd=mt_rand(0,1);
if ($evenOrOdd == 1)
{
$bankroll += $startBet;
echo "Win ...... Bankroll is now: " . $bankroll . "<br>";
}
else
{
$bankroll -= $startBet;
echo "Loss ..... Bankroll is now: " . $bankroll . "<br>";
}
}
echo "Probability, the Devourer of all Things!";
}
else
{
echo "Please enter a bankroll and starting bet above.";
}
?>
The form to it:
<form action="index.php" method="post">
Bankroll: <input type="text" name="pbankroll">
Start Bet: <input type="text" name="pstartbet">
<input type="submit">
</form>
I appreciate the help.
The HTML name pstartbet needs to be changed to pstartBet.
Edit to clarify:
The Start Bet input element in the HTML form has the name pstartbet with the 'B' in lowercase. When PHP checks for that value, it's looking for pstartBet with the B capitalized. One of these two names needs to be changed so the cases match.
As it is:
$startBet = $_POST["pstartBet"]; // doesn't exist
This means that $startBet will be null. When cast to a number by the mathematical operations this will result in 0 - so the value of $bankroll will never change, and the loop will continue forever.
First, you'll have to convert the incoming values to integer before using them in numerical operations:
$bankroll = intval($_POST["pbankroll"]);
$startBet = intval($_POST["pstartBet"]);
Or if they are float values use:
$bankroll = floatval($_POST["pbankroll"]);
$startBet = floatval($_POST["pstartBet"]);
Beside from this, the code can of course run forever. This is because of the pseudo randum numbers that are being used. If over a long time there are more 1's then 0's generated by mat_rand() then the code will run forever
Consider that truly random numbers cannot be generated by a computer. Apparently mt_rand generates a pseudo-random number in such a way that it's causing an infinite loop.
I would recommend setting the variables outside of the if clause & setting a default of '' which basically means 'empty' & then having the if check if those two variables are empty or not.
<?php
$bankroll = array_key_exists("pbankroll", $_POST) ? intval($_POST["pbankroll"]) : '';
$startBet = array_key_exists("pstartbet", $_POST) ? intval($_POST["pstartbet"]) : '';
if (!empty($bankroll) && !empty($startBet))
{
//If using this code below instead of that above, everything will work fine:
//$bankroll = 200;
//$startBet = 25;
while($bankroll >= $startBet)
{
$evenOrOdd=mt_rand(0,1);
if ($evenOrOdd == 1)
{
$bankroll += $startBet;
echo "Win ...... Bankroll is now: " . $bankroll . "<br>";
}
else
{
$bankroll -= $startBet;
echo "Loss ..... Bankroll is now: " . $bankroll . "<br>";
}
}
echo "Probability, the Devourer of all Things!";
}
else
{
echo "Please enter a bankroll and starting bet above.";
}
?>