keep adding value in php - php

Initially,the $number = 0. After 1st time clicking Add button, the value becomes 10. When 2nd time clicking, the value is changed to 20. then 3rd time is 30, 4th time 40.
Below is my code, is there anyone know how to fix it? Thanks!
<?php
$number = 0;
if(isset($_POST['add'])){
$number = $number +10;
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="<?php echo $_SERVER['SCRIPT_NAME']; ?>">
<?php echo $number; ?>
<input type="submit" name="add" value="Add" />
</form>
</body>
</html>

<input type="hidden" value="<?php echo $number ?>" name="number" />
Now change the $_POST['add'] to $_POST['number']
And $number = $_POST['number'] + 10;

This is fundamental to how PHP works.
There is no 'state' in between requests. This means that everything will be forgotten for every request. So if you want to retain data, you have to store it somewhere.
A couple of options:
A database such as MySQL
A session
A cookie
A caching system such as APC

First of all, your PHP needs a little adjusting:
<?php
$number = ($_POST['add'] != '') ? 0 : $_POST['add'];
$number += 10;
?>
<html>
Then add a hidden input above the <input type="submit">, like so:
<input type="hidden" name="add" value="<?php echo $number; ?>">

Use the session variable to retain the value per page request. Simple variable values is destroyed once script finish execution. Session variable will keep the value.
Read more about session
or use the database.

You need to save the value somehow. Either you use a database, like MySql, or you could save the value in a session variable.

Related

First element in array keeps getting overwritten, will not add onto array

I am trying to create a quiz, in order to do this I am using a form which users will input information into, once they submit this form it should add the input to an array/list.
The user should then be able to enter information and the process would repeat.
The finished product would be an array with each element corresponding to the order the answers were given.
-
I have tried so far using both array_push() and declaring elements, eg: $my_array[0] = $input;.
The current problem I am experiencing is that each time I submit the form, the $count variable doesn't seem to increment.
Instead it simply stores the data in the first element and overwrites which was previously there.
I am inclined to believe this is a problem with the posting of the submit button.
-
Here is my code:
<html>
<body>
<form action="" method="POST">
<input type="text" name="INPUT" placeholder="Input something"; required /><br><br>
<input type="submit" name="Submit" /><br><br>
<?PHP
$my_array = array();
$count = 0;
if(isset($_POST['Submit'])){
global $count;
$input = $_POST['INPUT'];
$my_array[$count] = $input;
print_r($my_array);
echo "Count:" . $count;
$count++;
}
?>
</form>
</body>
</html>
The crux of the issue here is that variable values do not persist across PHP requests. Every time you submit the form, you are throwing away your old $count and $my_array variables and initializing new variables with the same names.
Here is a working version of your code snippet, which takes advantage of the PHP $_SESSION variable to have persistent information between requests:
<?php
session_start();
if (!isset($_SESSION["my_array"])) {
$_SESSION["my_array"] = array();
}
?>
<html>
<body>
<form action="" method="POST">
<input type="text" name="INPUT" placeholder="Input something"; required /><br><br>
<input type="submit" name="Submit" /><br><br>
<?php
if(isset($_POST['Submit'])){
array_push($_SESSION["my_array"], $_POST['INPUT']);
print_r($_SESSION["my_array"]);
echo "Count:" . count($_SESSION["my_array"]);
}
?>
</form>
</body>
</html>

Pass variable from one page to another, then discard it

Is there a way I can pass a variable from one page to another but it only work on the next page clicked? After that it can be discarded/destroyed.
I've tried a php session but can't seem to kill the session on the next page clicked... or even if that way may be the wrong way to approach it.
Here's my session code:
<?php
session_start();
$x = $category;
$_SESSION['sessionVar'] = $x;
echo "$x";
?>
<?php
session_start();
$x = $_SESSION['sessionVar'];
echo "$x";
?>
I want to do this without having to submit a form.
You can pass a variable via a php session and then unset the variable on the following page.
$_SESSION['my_var'] = "some data";
$_SESSION['my_var'] = null;
unset($_SESSION['my_var']);
Send it as POST:
<form action="nextpage.php" method="post">
<input type="hidden" name="yourvariable" value="12345" />
<input type="submit" name="submit" value="Next page" />
</form>
Is it what was supposed?

Session variable not working

I am using one session variable in my php page. As per my infomation, it is accessible throughout the program and it is, but problem is that it is showing different value for the same variable at different place in php page?
the code is as follows
<html><body>
<?php session_start();
if(!isset($_SESSION['x']))
$_SESSION['x']=1;
echo "X=". $_SESSION['x'];
?>
<form>
<input type="submit" name="save" value="save" />
</form>
<?php
if (isset($_GET['save']))
{
if(isset($_SESSION['x']))
$_SESSION['x'] = $_SESSION['x']+1;
echo $_SESSION['x']."<br>";
}
else
echo "no submit";
?>
</body></html>
value becomes different before and after submit button click? Please tell me why it is so?
thanks in advavnce.
You are redeclaring the value of session variable 'x' here
$_SESSION['x'] = $_SESSION['x']+1;
This is why its appearing 1 greater than its initial value.
it is due to the code itself
if(isset($_SESSION['x'])) //It is set
$_SESSION['x'] = $_SESSION['x']+1; //Add 1 to the value
echo $_SESSION['x']."<br>"; return value with +1
Solution
The reason the output is different is the order you echo and update
//Echo
//Update Value
//Echo again
Simple solution would be to move this
if (isset($_GET['save']))
{
if(isset($_SESSION['x']))
$_SESSION['x'] = $_SESSION['x']+1;
echo $_SESSION['x']."<br>";
}
else
echo "no submit";
to above this
if(!isset($_SESSION['x']))
$_SESSION['x']=1;
echo "X=". $_SESSION['x'];
Also note set the method and the action in the form to make sure it calls itself
<form method="GET" action="[url to itself]">
<input type="submit" name="save" value="save" />
</form>
Do it like this :
<html><body>
<?php session_start();
if(!isset($_SESSION['x']))
$_SESSION['x']=1;
echo "X=". $_SESSION['x'];
?>
<form method="GET" action="">
<input type="submit" name="save" value="save" />
</form>
<?php
if (isset($_GET['save']))
{
if(isset($_SESSION['x']))
echo $_SESSION['x']."<br>";
}
else
echo "no submit";
?>
</body></html>
this way the code prints out the same value after submit as it did before.
Either way you try if you print value and change after or change value and print after, when page reloads it will change value. you could add another button called increment and add the following code inside the php :
if (isset($_GET['inc']))
{
if(isset($_SESSION['x']))
$_SESSION['x'] = $_SESSION['x']+1;
}
and this one inside the form:
<input type="submit" name="inc" value="inc" />
this way youre variable increment when you press the inc button

Incrementing variable in php after action is processed?

Aim of my Program:
On my index.php file, an image is displayed.
I want that, when i user clicks that image, a new image should be displayed.
And when he clicks the new image, another new image should appear.
What have i done till now ?
<?php
$mycolor = array("red.jpg", "green.jpg", "blue.jpg");
$i = 0;
$cc = $mycolor[$i++];
?>
<form method="post" action="index2.php">
<input type="image" src="<?php echo $cc; ?>">
</form>
I know what the error is. Whenever, the page is reloaded, the variable $i is initialized to ZERO. How, do i fix that. How can I retain the incremented value after the image is clicked ?
Also, I have no Javascript Knowledge. So, if possible explain me in terms of php.
You have different possibilities to remember $i. e.g:
$_GET: http://php.net/manual/en/reserved.variables.get.php
Cookies: http://php.net/manual/en/function.setcookie.php
Sessions: http://php.net/manual/en/features.sessions.php
There is also no necessity to use a form for this problem. Just wrap the image with a hyperlink and modify the url by incrementing the parameter (index.php?i=1, index.php?i=2, index.php?i=3 and so on).
<?php
$mycolor = array("red.jpg", "green.jpg", "blue.jpg");
if (isset($_POST['i'])) { // Check if the form has been posted
$i = (int)$_POST['i'] + 1; // if so add 1 to it - also (see (int)) protect against code injection
} else {
$i = 0; // Otherwise set it to 0
}
$cc = $mycolor[$i]; // Self explanatory
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="image" src="<?php echo $cc; ?>">
<input type="hidden" name="i" value="<?php echo $i; ?>"> <!-- Here is where you set i for the post -->
</form>
You can either use sessions, cookies or a POST variable to keep track of the index, but some how you need to remember the last index so you can +1 it. Here's an example using another (hidden) post variable:
<?php
// list of possible colors
$mycolor = array('red.jpg', 'green.jpg', 'blue.jpg');
// if a previous index was supplied then use it and +1, otherwise
// start at 0.
$i = isset($_POST['i']) ? (int)$_POST['i'] + 1 : 0;
// reference the $mycolor using the index
// I used `% count($mycolor)` to avoid going beyond the array's
// capacity.
$cc = $mycolor[$i % count($mycolor)];
?>
<form method="POST" action="<?=$_SERVER['PHP_SELF'];?>">
<!-- Pass the current index back to the server on submit -->
<input type="hidden" name="id" value="<?=$i;?>" />
<!-- display current image -->
<input type="button" src="<?=$cc;?>" />
</form>

How to do + or - in php?

I want to have a form in following way:
[-] [value] [+]
I don't know how to script the logic to get the value 1 higher or 1 lower in PHP.
I assumed something like following would work:
<?php
$i = 0;
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if(isset($_POST['plus']))
{
$i++;
}
if(isset($_POST['min']))
{
$i--;
}
}
?>
and my form is as following:
<form action="" method="post">
<input type="submit" name="min" value="-"> <input type="text" value=<?php echo $i ?> > <input type="submit" name="plus" value="+">
</form>
But I'm only getting either a 1 or a -1. Can someone show me how to do this in a good way?
Try this:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$i = $_POST['current_value'] || 1;
if(isset($_POST['plus']))
{
$i++;
}
if(isset($_POST['min']))
{
$i--;
}
}
?>
and this:
<form action="" method="post">
<input type="submit" name="min" value="-"> <input name="current_value" type="text" value=<?php echo $i ?> > <input type="submit" name="plus" value="+">
</form>
You need some way to get the current value to persist between requests - depending on your use case, you may need database storage as Rocket mentions, or this simple passing back of the current value may be enough.
PHP will simply load code on the server-side and run when the page is loaded. If you are looking to dynamically increment/decrement the value while remaining on the same page, I suggest you look into learning Javascript and jQuery.
Reference: https://developer.mozilla.org/en/JavaScript/
Reference: http://jQuery.com/
What is happening with your code is that you are incrementing a global variable that you set to 0 in the beginning. That is why the only values you get back or 1 or -1. This can be fixed by passing the variable you increment each time instead of using a global variable. That way it keeps the value between each plus and minus and doesn't keep resetting it.

Categories