Consider this markup:
<?php
$drill = 0;
$result = '';
$dynamicD = rand(5,15);
$num01 = $dynamicD-4;
$placeholder = $num01.'+4';
if($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["drill"])){
$humanErr = "Empty";
}
else {
$drill = $_POST["drill"];
if($drill !== $dynamicD) {
$result = "No";
}
else {
$result = "Yes";
}
};
};
?>
<!doctype html>
<html>
<body>
<p>Correct Answer: <?php echo $dynamicD ?></p>
<p>Does this work? <?php echo "$result";?></p>
<form method="post">
<fieldset>
<label for="drill">Can you solve it?</label>
<input type="text" name="drill" id="drill" maxlengh="2" placeholder="<?php echo $placeholder ?>" required="true" />
</fieldset>
<button type="submit" name="check">Check</button>
</form>
</body>
</html>
Basically it generates "random" number, insert it as a drill, and then let the user submit his answer. The problem is that the answer is always "NO"*.
I tried to separate the condition to this:
if($drill > $dynamicD) { $result = "bigger" }
elseif ($drill < $dynamicD) { $result = "smaller" }
and so on - but can't understand the logic of the $result (sometime bigger, sometime smaller, but i ALWAYS enter $dynamicD...).
What am i doing wrong here???
EDIT:
As the comments points, every time the page submit it generates new numbers. The first time the code execute is the only time that correct answer would be equal to the numbers that display. After the first submit there is a gap.
Note for future readers: The above code extracted and simplified from bigger and much complex system. Not something that anyone would want to just copy-paste.
The solution i choose was to store the dynamically created vars on a session and re-declare if the answer is correct.
Would love to hear about other ways (not client side).
Related
Can someone help me to figure out how to replace a defined string value with user input value? I am quite new in PHP programming and could not find an answer. I saw a lot of ways to replace string on the internet by using built-in functions or in arrays, but I could not find out the right answer to my question.
Here is my code:
$text = "Not found";
if ( isset($_GET['user'])) {
$user_input = $_GET['user'];
}
// from here I I tried to replace the value $text to user input, but it does not work.
$raw = TRUE;
$spec_char = "";
if ($raw) {
$raw = htmlentities($text);
echo "<p style='font-style:bold;'> PIN " . $raw . "</p>"; *# displays "Not found"*
} elseif (!$raw == TRUE ) {
$spec_char = htmlspecialchars($user_input);
echo "<p>PIN $spec_char </p>";
}
<form>
<input type="text" name="user" size="40" />
<input type="submit" value="User_val"/>
</form>
I appreciate your answers.
Lets run over your code, line by line.
// Set a default value for $text
$text = "Not found";
// Check if a value has been set...
if (isset($_GET['user'])) {
// But then create a new var with that value.
// Why? Are you going to change it?
$user_input = $_GET['user'];
}
// Define a few vars
$raw = TRUE;
$spec_char = "";
// This next line is useless - Why? Because $raw is always true.
// A better test would be to check for $user_input or do the
// isset() check here instead.
if ($raw) {
// Basic sanity check, but $text is always going to be
// "Not found" - as you have never changed it.
$raw = htmlentities($text);
// render some HTML - but as you said, always going to display
// "Not found"
echo "<p style='font-style:bold;'> PIN " . $raw . "</p>";
} elseif (!$raw == TRUE ) {
// This code is never reached.
$spec_char = htmlspecialchars($user_input);
echo "<p>PIN $spec_char </p>";
}
// I have no idea what this HTML is for really.
// Guessing this is your "input" values.
<form>
<input type="text" name="user" size="40" />
<input type="submit" value="User_val"/>
</form>
Just a guess I think you really wanted to do something more like this:
<?php
// Check if a value has been posted...
if (isset($_POST['user'])) {
// render some HTML
echo '<p style="font-style:bold"> PIN '.htmlspecialchars($_POST['user']).'</p>';
}
?>
<form method="post" action="?">
<input type="text" name="user" size="40" />
<input type="submit" value="User_val"/>
</form>
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 3 years ago.
I am new to PHP and working on an assignment. I'm almost finished but feel like I'm beating my head against the wall with this last step.
The user chooses a survey and then answers 10 questions. After the 10th question is answered, they are redirected to the results.php page which should display their questions and answers.
I know that I need to use a foreach loop but this is my first time working with them. I've finished multiple sites to get an understanding of how they work but the examples are not helping me to understand how to make it work in my assignment.
Right now I get this when I run the file:
Parse error: syntax error, unexpected 'endforeach' (T_ENDFOREACH), expecting end of file in C:\xampp\htdocs\sandbox\HW4\results.php on line 38
When I remove the endforeach, I'm told that $answer within the echo is undefined.
I've run out of ways to change my loop. Nothing works. Some help would be appreciated. I apologize if I include code that is not relevant to my problem.
With little understanding of PHP, I'm not quite sure what I need to include and what I don't. I'm including code from my survey.php file that includes the array session and my code from the results file that should contain my foreach loop.
Thank you for your time.
$isPostBack = filter_input(INPUT_POST, 'submitButton') !== NULL;
if ($isPostBack) {
// This is what happens if there is a postback.
$choose_survey = filter_input(INPUT_POST, 'choose_survey', FILTER_VALIDATE_INT);
if ($choose_survey !== NULL) {
// Check the value of $choose_survey and then set 'survey' accordingly, e.g.
// These numbers are the keys to the arrays with the list of surveys
switch ($choose_survey) {
case 0:
$_SESSION['survey'] = $survey0;
break;
case 1:
$_SESSION['survey'] = $survey1;
break;
case 2:
$_SESSION['survey'] = $survey2;
break;
default:
break;
}
$_SESSION['answers'] = array();
$_SESSION['number'] = 1;
} else {
// A survey is not selected because it was already chosen.
// get the value from the radio button.
$answer = filter_input(INPUT_POST, 'answer', FILTER_DEFAULT);
if ($answer == NULL) {
echo '<p>Please select an answer before clicking Submit.</p>';
} else {
$question_key = filter_input(INPUT_POST, 'question_key', FILTER_VALIDATE_INT);
$question = $_SESSION['survey'][$question_key];
// this will be used later to display the answers/results
$_SESSION['answers'][$question] = $answer;
unset($_SESSION['survey'][$question_key]);
// This is adding 1 to the question number unless session number is 10
if ($_SESSION['number'] == 10) { // if = to 10 then we redirect to next page.
header('Location: results.php');
} else { // If number is less than 10, we add 1
$_SESSION['number'] += 1;
}
}
}
} else {
// This is what happens if there is no postback.
}
?>
results.php file
<br /> <p>Thank you for participating in the survey!</p>
<html lang="en">
<head>
<title>Survey Results</title>
<link rel="stylesheet" type="text/css" href="">
</head>
<body>
<form action="logout.php">
<p>Here are your results</p>
<input type="submit" id="submit" value="Logout" />
</form>
<section>
<?php foreach ($_SESSION['answers'] as $question => $answer) ?>
<p>
<?php echo "$answer <br/>"; ?>
</p>
<?php endforeach; ?>
</section>
</body>
did you loaded the session_start() on your file? If not this may not enable to save your sessions that you are setting. Also on your results.php you can change your code to:
<?php foreach($_SESSION['answers'] as $question => $answer){ ?>
<p>
<?php echo $answer."<br/>"; ?>
</p>
<?php }
?>
Hope this helps!
I am not sure, but maybe you could place <?php session_start();?> at the beginning of your results.php to make your script able to work with $_SESSION variable?
Also try to var_dump($_SESSION); as in result.php, just in case.
I surprised that nobody noticed the syntax error in the foreach.
If you want to use the endforeach style, you can change your code like this (this is called Alternative Syntax):
<section>
<?php foreach ($_SESSION['answers'] as $question => $answer): ?>
<p>
<?php echo "$answer <br/>"; ?>
</p>
<?php endforeach; ?>
</section>
Or if you want to use PHP-way to make a foreach, you can write it like this:
<section>
<?php foreach ($_SESSION['answers'] as $question => $answer) { ?>
<p>
<?php echo "$answer <br/>"; ?>
</p>
<?php } ?>
</section>
However, for cleaner HTML & PHP code, I suggest you to write it like this:
<section>
<?php
foreach ($_SESSION['answers'] as $answer) {
echo "<p>$answer</p>" . PHP_EOL;
}
?>
</section>
Note that I removed unused $question variable.
My code should provide two random numbers and have the user enter their product (multiplication).
If you enter a wrong answer, it tells you to guess again, but keeps the same random numbers until you answer correctly. Answer correctly, and it starts over with a new pair of numbers.
The below code changes the value of the two random numbers even if I entered the wrong number. I would like to keep the values the same until the correct answer is entered.
<?php
$num1=rand(1, 9);
$num2=rand(1, 9);
$num3=$num1*$num2;
$num_to_guess = $num3;
echo $num1."x".$num2."= <br>";
if ($_POST['guess'] == $num_to_guess)
{ // matches!
$message = "Well done!";
}
elseif ($_POST['guess'] > $num_to_guess)
{
$message = $_POST['guess']." is too big! Try a smaller number.";
}
elseif ($_POST['guess'] < $num_to_guess)
{
$message = $_POST['guess']." is too small! Try a larger number.";
}
else
{ // some other condition
$message = "I am terribly confused.";
}
?>
<!DOCTYPE html>
<html>
<body>
<h2><?php echo $message; ?></h2>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="answer" value="<?php echo $answer;?>">
<input type="hidden" name="expression" value="<?php echo $expression;?>">
What is the value of the following multiplication expression: <br><br>
<?php echo $expression; ?> <input type="text" name="guess"><br>
<input type="submit" value="Check">
</form>
</body>
</html>
In order to keep the same numbers, you have to store them on the page and then check them when the form is submitted using php. You must also set the random number if the form was never submitted. In your case, you were always changing num1 and num2. I tried to leave as much of your original code intact, but it still needs some work to simplify it.
First I added 2 more hidden field in the html called num1 and num2
Second, I set $num1 and $num2 to the value that was submitted from the form.
After following the rest of the logic, I make sure that $num1 and $num2 are reset if the answer is correct of it the form was never submitted.
You can see the comments in the code below.
Additionally, if you were going to use this in a production environment, you would want to validate the values being passed in from the form so that malicious users don't take advantage of your code. :)
<?php
// Setting $num1 and $num2 to what was posted previously and performing the math on it.
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$num_to_guess = $num1*$num2;
// Check for the correct answer
if ($_POST && $_POST['guess'] == $num_to_guess)
{
// matches!
$message = "Well done!";
$num1=rand(1, 9);
$num2=rand(1, 9);
}
// Give the user a hint that the number is too big
elseif ($_POST['guess'] > $num_to_guess)
{
$message = $_POST['guess']." is too big! Try a smaller number.";
}
// Give the user a hint that the number is too small
elseif ($_POST['guess'] < $num_to_guess)
{
$message = $_POST['guess']." is too small! Try a larger number.";
}
// If the form wasn't submitted i.e. no POST or something else went wrong
else
{
// Only display this message if the form was submitted, but there were no expected values
if ($_POST)
{
// some other condition and only if something was posted
$message = "I am terribly confused.";
}
// set num1 and num2 if there wasn't anything posted
$num1=rand(1, 9);
$num2=rand(1, 9);
}
// Show the problem
echo $num1."x".$num2."= <br>";
?>
<!DOCTYPE html>
<html>
<body>
<h2><?php echo $message; ?></h2>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="num1" value="<?= $num1 ?>" />
<input type="hidden" name="num2" value="<?= $num2 ?>" />
<input type="hidden" name="answer" value="<?php echo $num3;?>">
<input type="hidden" name="expression" value="<?php echo $expression;?>">
What is the value of the following multiplication expression: <br><br>
<input type="text" name="guess"><br>
<input type="submit" value="Check">
</form>
</body>
</html>
When you load the page for the first time, you have (i.e.) “2*3” as question. $_POST is not defined, so if ($_POST['guess']... will produce a undefined index warning. Then you echo $message, but where you define $message? $_POST['guess'] is undefined, so is evaluated as 0, $num_to_guess is 6 (=2*3), so $message is set to " is too small! Try a larger number.", even if the user has not input anything. The hidden answer is set to $answer, but this variable is not defined so it is set to nothing (or to “Notice: Undefined variable: answer”, if you activate error reporting). Same issue for expression input and for echo $expression.
Try something like this:
$newQuestion = True; // This variable to check if a new multiplication is required
$message = '';
/* $_POST['guess'] check only if form is submitted: */
if( isset( $_POST['guess'] ) )
{
/* Comparison with answer, not with new result: */
if( $_POST['guess'] == $_POST['answer'] )
{
$message = "Well done!";
}
else
{
/* If result if wrong, no new question needed, so we propose same question: */
$newQuestion = False;
$answer = $_POST['answer'];
$expression = $_POST['expression'];
if( $_POST['guess'] > $_POST['answer'] )
{
$message = "{$_POST['guess']} is too big! Try a smaller number.";
}
else
{
$message = "{$_POST['guess']} is too small! Try a larger number.";
}
}
}
/* New question is generated only on first page load or if previous answer is ok: */
if( $newQuestion )
{
$num1 = rand( 1, 9 );
$num2 = rand( 1, 9 );
$answer = $num1*$num2;
$expression = "$num1 x $num2";
if( $message ) $message .= "<br>Try a new one:";
else $message = "Try:";
}
?>
<!DOCTYPE html>
(... Your HTML Here ...)
This might also be fun to learn. This is a session. Lets you store something temporarily. It is a little dirty. But fun to learn from.
http://www.w3schools.com/php/php_sessions.asp
<?php
session_start(); // Starts the Session.
function Save() { // Function to save $num1 and $num2 in a Session.
$_SESSION['num1'] = rand(1, 9);
$_SESSION['num2'] = rand(1, 9);
$_SESSION['num_to_guess'] = $_SESSION['num1']*$_SESSION['num2'];;
$Som = 'Guess the number: ' . $_SESSION['num1'] .'*' .$_SESSION['num2'];
}
// If there is no session set
if (!isset($_SESSION['num_to_guess'])) {
Save();
$message = "";
}
if (isset($_POST['guess'])) {
// Check for the correct answer
if ($_POST['guess'] == $_SESSION['num_to_guess']) {
$message = "Well done!";
session_destroy(); // Destroys the Session.
Save(); // Set new Sessions.
}
// Give the user a hint that the number is too big
elseif ($_POST['guess'] > $_SESSION['num_to_guess']) {
$message = $_POST['guess']." is too big! Try a smaller number.";
$Som = 'Guess the number: ' . $_SESSION['num1'] .'*' .$_SESSION['num2'];
}
// Give the user a hint that the number is too small
elseif ($_POST['guess'] < $_SESSION['num_to_guess']) {
$message = $_POST['guess']." is too small! Try a larger number.";
$Som = 'Guess the number: ' . $_SESSION['num1'] .'*' .$_SESSION['num2'];
}
// some other condition
else {
$message = "I am terribly confused.";
}
}
?>
<html>
<body>
<h2><?php echo $Som . '<br>'; ?>
<?php echo $message; ?></h2>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="guess"><br>
<input type="submit" value="Check">
</form>
</body>
</html>
Im in this page: website.php?page=5 and in this page I have this form:
<form method="POST" action="website.php?page=<?php echo $pagenumber; ?>">
<input type="text" name="goto" />
<input type="submit" name="submit" value="goto" />
</form>
If I write something like 3 into the text field and press the goto button (if isset.... my php code get the number and upload into the $pagenumber var)
But the new page isn't the website.php?page=3 what I want. The new page is website.php?page= (there is no number) .and if I press again then goes it to the right page.
I think in the first press when i do the $pagenumber isn't declared. Only when i press second.
How can I fix it? I must use this way i cant use session, cookie etc.
<?php if(isset($_POST['submit']))
{
$kitkeresek = $_POST['goto'];
$becsuletemw = "SELECT * FROM adatok WHERE nev = '$kitkeresek'";
$becsuletem2w = mysql_query($becsuletemw);
while( $becsuletem3w = mysql_fetch_array($becsuletem2w))
$becsuletemw = $becsuletem3w["becsulet"];
$valllamiw = mysql_query("SELECT becsulet FROM adatok WHERE becsulet > '$becsuletemw' ");
$rowsw = mysql_num_rows( $valllamiw );
$kitkeresekw = $rowsw + 1 ;
$intvizsgalat= $kitkeresekw/10;
if (is_int($intvizsgalat))
{ $pagenumber = $intvizsgalat - 1 ; }
else
{$pagenumber = floor($kitkeresekw/10); } ;
}
?>
When you do this :
$intvizsgalat= $kitkeresekw/10;
$intvizsgalat is float, even if the result is int, because it is the result of a division.
You can try var_dump($intvizsgalat) to confirm
try something like this:
$floatParts = $intvizsgalat - floor(intvizsgalat);
if ($floatParts == 0) {
//
} else {
//
}
Ok so I have a form with 1 input and a submit button. Now I am using an if/else statement to make three acceptable answers for that input. Yes, No, or anything else. This if/else is working the thing is the code is kicking out the else function as soon as the page is loaded. I would like there to be nothing there until the user inputs then it would show one of three answers.
Welcome to your Adventure! You awake to the sound of rats scurrying around your dank, dark cell. It takes a minute for your eyes to adjust to your surroundings. In the corner of the room you see what looks like a rusty key.
<br/>
Do you want to pick up the key?<br/>
<?php
//These are the project's variables.
$text2 = 'You take the key and the crumby loaf of bread.<br/>';
$text3 = 'You decide to waste away in misery!<br/>';
$text4 = 'I didnt understand your answer. Please try again.<br/>';
$a = 'yes';
$b = 'no';
// If / Else operators.
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
}
if ($usertypes == $a){
echo ($text2);
}
elseif ($usertypes == $b){
echo ($text3);
}
else {
echo ($text4);
}
?>
<form action="phpgametest.php" method="post">
<input type="text" name="name" /><br>
<input type="submit" name="senddata" /><br>
</form>
You just need to call the code only when the POST value is set. This way it will only execute the code when the form was submitted (aka $_POST['senddata'] is set):
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
if ($usertypes == $a){
echo ($text2);
}
elseif ($usertypes == $b){
echo ($text3);
}
else {
echo ($text4);
}
}
Just put the validation in the first if statement like this:
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
if ($usertypes == $a) {
echo ($text2);
} elseif ($usertypes == $b) {
echo ($text3);
} else {
echo ($text4);
}
}
When you load your page the browser is making a GET request, when you submit your form the browser is making a POST request. You can check what request is made using:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Your form was submitted
}
Put this around your form processing code in order to keep it from being executed on GET request.