Using Session Tracking for Multipage Form in PHP - 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>

Related

add values with one another with input field submit in php calculator

I want a calculator with my PHP code that adds values with one after one with submit button.like when I input a number then submit it and show it on the page then and input other, it should add previous number.and then enter another then submit.like these, numbers are adding with one another after submitting.
<?php
session_start();
?>
<?php
error_reporting(0);
?>
<html>
<title>adding input single values</title>
<body>
<form method="post">
<input type="text" name='number' method="post"/>
<input type="submit" />
</form>
<?php
if(!isset($_POST['number']))
{
}
else
{
$sum += $_POST['number'];
echo ++$sum;
}
?>
</body>
</html>
here is the output
You could use a hidden field instead of storing in the session.
<input type="text" name='number' method="post"/>
<?php
if(!isset($_POST['number'])) {
echo "<input type='hidden' name='prev_number' value=0 />";
} else {
$sum = $_POST['number'] + $_POST['prev_number'];
echo "<input type='hidden' name='prev_number' value=" . $sum . " />";
echo $sum;
}
?>
<input type="submit" />
</form>
<?php
if(!isset($_POST['number'])) {
// ...
}
else {
$_SESSION['number'] = isset($_SESSION['number']) ? $_SESSION['number'] : '';
$_SESSION['number'] += $_POST['number'];
echo $_SESSION['number'];
}

Use a single textbox to keep adding values to array after post

So I'm currently working on a little project that allows a user to input a number into a textbox, after clicking a button that says "add" it should store that value into an array and then allow the user to input another value into that array. There is also a button on the page when the user is finished and wants to sum the values called "Submit". The problem I'm running into is everytime the form posts back, it recreates a new blank array. Any tips?
See the code below:
<html>
<head>
</head>
<body>
<h2>Please Select your title and name:</h2>
<form action='<?php echo $_SERVER["PHP_SELF"]; ?>' method='post'>
<p>
<label for="strFirstname">Type number to add: </label>
<input type='text' name='strNumber' id='strNumber'/>
</p>
<p>
<input type='submit' name='submit' value='Add' />
</p>
<p>
<input type='submit' name='calculate' value='Compute' />
</p>
<?php
$array = array();
if (isset($_POST['submit']))
$num = $_POST['strNumber'];
$array[] = $num;
foreach($array as $num)
echo $num . ' + ';
if(isset($_POST['calculate']))
foreach($array as $num)
echo $num . ' + ';
?>
</form>
</body>
</html>
<?php
session_start();
?>
<html>
<head>
</head>
<body>
<h2>Please Select your title and name:</h2>
<form action='' method='post'>
<p>
<label for="strFirstname">Type number to add: </label>
<input type='text' name='strNumber' id='strNumber'/>
</p>
<p>
<input type='submit' name='submit' value='Add' />
</p>
<p>
<input type='submit' name='calculate' value='Compute' />
<input type='submit' name='clear' value='clear' />
</p>
<?php
if (isset($_POST['submit'])) {
if(!array_key_exists("numbers", $_SESSION)) {
$_SESSION["numbers"] = array();
}
array_push($_SESSION["numbers"], $_POST["strNumber"]);
}
if(isset($_POST['clear'])) {
$_SESSION["numbers"] = array();
}
if(array_key_exists("numbers", $_SESSION)) {
echo implode("+", $_SESSION["numbers"]);
}
if(isset($_POST['calculate'])) {
if(array_key_exists("numbers", $_SESSION)) {
$expression = implode("+", $_SESSION["numbers"]);
eval( '$result = (' . $expression . ');' );
echo "=" . $result;
}
}
?>
</form>
</body>
</html>
Start a session
When the action is "submit"
Check if the session which will store the numbers is initialized
If it's not initialize it as an array
Finally push the number into the array
Check if there is a session initialized if there is print all the numbers ( you can use implode to do that)
if the action is calculate .. just make the calculation ( check eval function )

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

PHP random number not working

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>

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