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

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 )

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'];
}

Table Generator

Hi I have a question about generating rows and columns. would like to ask about how can I make it in one page only. This is what I have tried.
HTML:
<html>
<head>
<title>Table Generator</title>
<body>
<center><h1>Generate Your Table</h1></center>
<div id="div1">
<center><h4>Enter number of Row and Column</h4>
<form action="get_table/execute_table.php" method="POST">
<label for="title">Row</label>
<input type="text" name="title1" placeholder="Row">
<br>
<label for="title">Column</label>
<input type="text" name="title2" placeholder="Column">
<br>
<input type="submit" name="submit" value="Generate Table"> </center>
</form>
</div>
</body>
PHP:
<?php
$row = $_POST['title1'];
$column = $_POST['title2'];
echo "<table border='1'>";
for($tr=1;$tr<=$row;$tr++){
echo "<tr>";
for($td=1;$td<=$column;$td++){
echo "<td>row: ".$tr." column: ".$td."</td>";
}
echo "</tr>";
}
echo "</table>";
?>
Yes, it is fully running but I want it in 1 page only. Thanks.
Normally, if you want it on the same page, you just omit the action="" with its value.
Then of course, put the php process in the same page as the form:
<div id="div1">
<center><h4>Enter number of Row and Column</h4>
<form action="" method="POST">
<!-- ^^ no more value, well you could just put the same filename -->
<label for="title">Row</label>
<input type="text" name="title1" placeholder="Row">
<br>
<label for="title">Column</label>
<input type="text" name="title2" placeholder="Column">
<br>
<input type="submit" name="submit" value="Generate Table"> </center>
</form>
</div>
<?php
$out = ''; // initialize a string holder and when the submission is done, concatenate all the strings
if(isset($_POST['submit'])) { // catch submission button
$row = $_POST['title1'];
$column = $_POST['title2'];
$out .= "<table border='1'>";
for($tr=1;$tr<=$row;$tr++){
$out .= "<tr>";
for($td=1;$td<=$column;$td++){
$out .= "<td>row: ".$tr." column: ".$td."</td>";
}
$out .= "</tr>";
}
$out .= "</table>";
}
echo $out; // finally echo it
to achieve this by using only one page just leave the action attribute empty. and add your php block on top.and make sure to save it as .php and place your php code block on top of all html
so in the end it will look like this
<?php
$row = $_POST['title1'];
$column = $_POST['title2'];
echo "<table border='1'>";
for($tr=1;$tr<=$row;$tr++){
echo "<tr>";
for($td=1;$td<=$column;$td++){
echo "<td>row: ".$tr." column: ".$td."</td>";
}
echo "</tr>";
}
echo "</table>";
?>
<html>
<head>
<title>Table Generator</title>
<body>
<center><h1>Generate Your Table</h1></center>
<div id="div1">
<center><h4>Enter number of Row and Column</h4>
<form action="" method="POST">
<label for="title">Row</label>
<input type="text" name="title1" placeholder="Row">
<br>
<label for="title">Column</label>
<input type="text" name="title2" placeholder="Column">
<br>
<input type="submit" name="submit" value="Generate Table"> </center>
</form>
</div>
</body>
You need to post to the same page, and check if the PhP Post array has data yet.
Replace the form action with:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST">
Note: although most (all?) browsers support self-posts with a blank action, this is not technically W3C compliant.
Then when the page is submitted it will reload the same page and populate the POST array. Somewhere on your page add a condition similar to:
if($_POST['title']){
//do whatever get_table/execute_table.php did
}else{
//echo the form here or, if you're allowed, use an include()
}
More info on self-posting:
How do I make a PHP form that submits to self?

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>

Stack array losing previous values for single page submission

I'm trying to do the push-and-pop stack array in PHP but only the last value is stored. How can I store the other values as well even if I click on the button again & load the same page?
This is what I've done:
<?php
if(!$_GET)
$myStack = array();
else
$myStack[] = "";
?>
<html>
<head> <title>Exercise</title>
</head>
<body>
<form action="test.php" method="get">
Element: <input type="text" name="num" value="0"/><br/>
<input type="submit" name="push" value="push" />
<input type="submit" name="pop" value="pop" />
</form>
<?php
if(isset($_GET["push"])){
array_push($myStack, $_GET["num"]);
foreach($myStack as $val)
echo $val . " ";
}
elseif(isset($_GET["pop"])){
array_pop($myStack);
foreach($myStack as $val)
echo $val . " ";
}
?>
</body>
</html>
Every http request php will execute script with all variables from scratch. You have to use $_SESSION or static variables to save values between requests. To store array in $_SESSION just assign it to key:
$_SESSION["myStack"] = array();
$_SESSION["myStack"][] = 1;
$_SESSION["myStack"][] = 2;
You have a reset at the top off your script. After reload your stack will be empty. Also you have to save your stack into a session var.
Here's the code with using a session to store the array:
<?php
//starts the session
session_start();
$myStack = array();
//gets the array from the session if it exists
if (isset($_SESSION['stack']))
$myStack = $_SESSION['stack'];
?>
<html>
<head> <title>Exercise</title>
</head>
<body>
<form action="test.php" method="get">
Element: <input type="text" name="num" value="0"/><br/>
<input type="submit" name="push" value="push" />
<input type="submit" name="pop" value="pop" />
</form>
<?php
if(isset($_GET["push"])){
array_push($myStack, $_GET["num"]);
foreach($myStack as $val)
echo $val . " ";
}
elseif(isset($_GET["pop"])){
array_pop($myStack);
foreach($myStack as $val)
echo $val . " ";
}
//stores the array in the opened session
$_SESSION['stack'] = $myStack;
?>
</body>
</html>

when perfoming a multiple row updates, how do i access other form element values, apart from the checkbox?

i wrote a piece of code to do multiple row deletions based on ticked check boxes.
Now i need to mordify it to do multiple row updates.
i have been failing to access the textbox values for each row.
here's my code, in general.
<?php
if (isset($_POST["SaveComments"]) && isset($_POST["SaveEachComment"]))
{
while(list($key, $val) = each($_POST["SaveEachComment"]))
{
if($val == 'commentbox')
{
// do the update here. $val contains the ID
}
}
}
?>
<form id="form1" name="form1" method="post" action="test.php">
<input type="checkbox" <?php echo 'name="SaveEachComment['.$row["comment"].']" ';?> value="commentbox" id="commentbox" />
<input type="text" name="rowcomment" size="55" value="<?php echo $comment;?>" />
<input type="submit" name="SaveComments" value="submit" />
</form>
I just added a for loop to print multiple form fields. Obviously your iteration would be as many as number of rows, so you can change that part of the code. But try this:
<?php
if (isset($_POST["SaveComments"]) && isset($_POST["SaveEachComment"]))
{
while(list($key, $val) = each($_POST["SaveEachComment"]))
{
if($val == 'commentbox')
{
echo $_POST['rowcomment'][$key] . "<br />\n";
// do the update here. $val contains the ID
}
}
}
?>
<form id="form1" name="form1" method="post" action="test.php">
<?php for ($i=0; $i<11; $i++) { ?>
<input type="checkbox" <?php echo 'name="SaveEachComment['.$i.']" ';?> value="commentbox" id="commentbox" />
<input type="text" name="rowcomment[<? echo $i?>]" size="55" value="<?php echo $comment;?>" />
<br />
<?php } ?>
<input type="submit" name="SaveComments" value="submit" />
</form>

Categories