Button click counter [PHP] - php

I tried to create a variable to store a count of button clicked. Unfortunetlly i get this error:
Undefined variable: counter
It's my code:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$counter = isset($_POST['counter']) ? $_POST['counter'] : 0;
if(isset($_POST["button"])){
$counter++;
echo $counter;
}
}
And it's a form:
<form action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method = post>
<input type = "submit" name = "button" value = "Submit" >
<input type = "hidden" name = "counter" value = "<?php print $counter; ?>"; />
</form>
Anybody know what i'm doing wrong?

Alternatively, if you want to save the counter, you can use sessions. Like this:
session_start();
// if counter is not set, set to zero
if(!isset($_SESSION['counter'])) {
$_SESSION['counter'] = 0;
}
// if button is pressed, increment counter
if(isset($_POST['button'])) {
++$_SESSION['counter'];
}
// reset counter
if(isset($_POST['reset'])) {
$_SESSION['counter'] = 0;
}
?>
<form method="POST">
<input type="hidden" name="counter" value="<?php echo $_SESSION['counter']; ?>" />
<input type="submit" name="button" value="Counter" />
<input type="submit" name="reset" value="Reset" />
<br/><?php echo $_SESSION['counter']; ?>
</form>
By the way, your current code will show an Undefined index error because you are echoing $counter on your form but you haven't initialized it yet. It will only exist, upon first form submission, not upon first normal load of the page.

There is no error in your code. Its working at my end. You need to check two points:
PHP code should be above on HTML, HTML code will come after PHP code. So that $counter variable will be initialized.
PHP and HTML code should be on same page.
As OP edited the question: So, the line $counter = isset($_POST['counter']) ? $_POST['counter'] : 0; should not be in if-block. To be sure, ** Make this line as a first line of PHP file. Then only $counter variable will be available for whole page.

Variable is not defined because of this u get this error.
To hide this error write this in top of page error_reporting(0).
Check this..how to defined variable?

you try to use a undelaired variable
<input type = "hidden" name = "counter" value = "<?php print $counter; ?>"; />
................................................................^
this var doesn't exists as the error says. guess you have a wrong setup of your code.
like the php is not on the same side or not above the html

Related

keep the previous value of variable after submitting the form in php

I have a form with a button "NEXT", which on clicked needs to change the value of a variable.I have initialized the variable as 0 and I want that as the NEXT button is getting clicked the variable should increment by 1.Since, I am also submitting the form when the button is clicked,so the variable is resetting to 0,it is not keeping the previous value.
html code is :
<form name="graph" enctype="multipart/form-data" method="POST" action="graph.php">
<input type="hidden" id="hdn" name ="hdn" value="">
<input type="button" id="btnNext" name ="btnNext" value="NEXT" onClick="nextfun();">
Onclicking NEXT, I am calling a javascript function that is submitting the form,
function nextfun()
{
var a= document.getElementById("hdn");
a.value="nextgroup";
document.graph.submit();
}
Now,when form is submitted, I am using php code to increment the value of variable.
$flag=0;
if(isset($_POST['hdn']))
{
if($_POST["hdn"]=="nextgroup")
{
$flag=$flag+1;
}
}
On the graph.php page do like this:-
<?php
session_start();
if(isset($_POST['hdn']))
{
if($_POST["hdn"]=="nextgroup")
{
if(isset($_SESSION['flag'])){
$_SESSION['flag'] = $_SESSION['flag']+1;
}else{
$_SESSION['flag'] = 1;
}
}
}
echo $_SESSION['flag'];
?>
Note:- first time Session value will 1and nxt onward on each submission it will increase by 1.
You can add to your HTML something like this:
<input type="hidden" name="prevValue" value="<?php echo $prev; ?>" />
You should submit this value too.
And in the PHP
$flag=0;
if(isset($_POST['hdn']))
{
if($_POST["hdn"]=="nextgroup")
{
$prev = $_POST["prevValue"];
$flag = $prev +1;
}
}

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