Stack array losing previous values for single page submission - php

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>

Related

Saving checkboxes in Session PHP

i need your help.
I'm trying to save the checkbox values in a session and show, on a second php file.
But the Session is in the second php file always NULL.
If i output the Session and the Post on the one.php, the array looks fine.
one.php
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<h1>Show checkboxes:</h1>
<form action="two.php" method="post">
<input type="checkbox" name="vehicle[]" value="Bike"> I have a bike<br>
<input type="checkbox" name="vehicle[]" value="Car"> I have a car<br>
<input type="checkbox" name="vehicle[]" value="Boat" checked> I have a boat<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
<?php
$_SESSION['test'] = $_POST['vehicle'];
var_dump($_POST['vehicle']);
echo "</br>";
var_dump($_SESSION['test']);
?>
two.php
<?php
session_start();
$arr = $_SESSION['test'];
var_dump($arr);
foreach($arr as $value)
{
echo $value;
echo "</br>";
}
?>

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 )

How to input two values into one field using implode

<?php include 'connection.php'; ?>
<?php
if (isset($_REQUEST['submit'])) {
$description1 = $_REQUEST['description1'];
$a = $description1;
$description2 = $_REQUEST['description2'];
$b = $description2;
$f = array('$a', '$b');
$g = implode(" ", $f);
echo $g;
$qr = mysql_query("insert into module1 values('','$g')");
}
?>
<html>
<head>
</head>
<body>
<form name="cform" method="post" enctype="multipart/form-data">
<input type="text" name="description1[]" /><br />
<input type="text" name="description2[]" /><br />
<input type="submit" name="submit" />
</form>
</body>
I want to insert the value of description1 & description2 into one feild of a table of database.. How to do that?
Use json_encode()
$f = json_encode(array('$a', '$b'));
Retrieve it using json_decode()
First of all you're sending arrays name="description1[]" so need to use $_REQUEST['description1'][0]
Awful lot of code just to do this
$g = $_REQUEST['description1'][0] . ' ' . $_REQUEST['description2'][0];
but since you asked specifically to use implode
$g = implode(' ', array($_REQUEST['description1'][0], $_REQUEST['description2'][0]));
You can use array_merge to merge your array
$f = array_merge($a, $b);
$g = implode(" ", $f);
echo $g;
The issue here is the way you named the fields. The square brackets make them arrays and so you would need to access $_REQUEST['description1'][0] instead.
Try this code, I cleaned it a little but kept it the same direction you were heading.
<?php include 'connection.php';?>
<?php
if(isset($_REQUEST['submit']))
{
$arrayDescription = array(
$_REQUEST['description1'],
$_REQUEST['description2']
);
$stringDescription = implode(' ', $arrayDescription);
echo $stringDescription
$qr = mysql_query("insert into module1 values('','$stringDescription')");
}
?>
<html>
<head>
</head>
<body>
<form name="cform" method="post" enctype="multipart/form-data">
<input type="text" name="description1" /><br />
<input type="text" name="description2" /><br />
<input type="submit" name="submit" />
</form>
</body>
In HTML why are you using array notation in description1[] and description2[] variables where as these two variables are totally different by name. Use description1 and description2 in names and on PHP side get values through $_POST['description1'] and $_POST['description2']. Rest of your code is correct.

Associative array can't echo data from input form

I insert data to the array from an input box. But I don't know why I can't print the associative array. I can only echo the latest data from the input box. I want to add data to the array and echo it every time I write to the input box.
<?php
$part_insert_message = "";
$inserted_parts = array();
session_start();
$part_inserted_id;
if(isset($_POST['submit'])) {
$part_inserted_id = $_POST['arrdata'];
$inserted_parts[$part_inserted_id] = $part_inserted_id;
echo sizeof($inserted_parts);
// store session data
$_SESSION['views']= $inserted_parts;
$part_insert_message = "ID: " . $part_inserted_id;
}
?>
<html>
<body>
<div>
<h2>Part</h2>
<form action="array_session_example.php" enctype="multipart/form-data" name="myForm" id="myform" method="post">
Array Data: <input type="text" name="arrdata"><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php echo $part_insert_message;
foreach($inserted_parts as $key => $value){
echo $key;
}
?>
</div>
</body>
</html>
You're creating a new array every time, and then adding that to the session. You'll need to check if an array has already been stored, and if it has add to that.
$inserted_parts = array();
session_start();
if(isset($_SESSION['views']) && is_array($_SESSION['views']))
$inserted_parts = $_SESSION['views'];

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