PHP Static variable reloads after Page Load - php

This is a simplified version of what I want to accomplish:
In my script I want a static variable x to be incremented every time the submit button is pressed.
<?php
function IncX(){
static $x = 0;
$x++;
echo $x;
}
?>
<body>
<form>
<input type="submit" name="submit" class="next btn btn-primary" value="Submit" />
</form>
</body>
But it initializes to x=0 on every page reload after submit.

You're loading the variable afresh every time the page loads, so it's always going to be the same.
The solution is to store it in a session and then increment it there. Include a conditional to create the variable if it doesn't already exist.
<?php
session_start();
if (!isset($_SESSION['x'])) {
$x = $_SESSION['x'];
} else {
$x = 0;
}
$x++;
echo $x;
$_SESSION['x'] = $x;
?>

<?php
session_start();
$x = 0;
if (isset($_SESSION['x'])) {
$x = $_SESSION['x'];
$x++;
} else {
$_SESSION['x'] = $x;
}
// /$x++;
echo $x;
$_SESSION['x'] = $x;
?>

Apache doesn't keep track of variables in php scrips between clicks, you would have to store it somewhere, be it the $_SESSION or a database.
Moreover, the static keyword doesn't do what you seem to think it does. It would work for successive calls of the function in a single run of the script, but not between clicks.
in any event, you can use the ternary operator to achieve this, would you happen to put it in the session. I've also added a check to make sure the variable is actually a viable count number:
session_start();
$_SESSION['x'] = isset($_SESSION['x']) && is_int($_SESSION['x'])
? $_SESSION['x'] + 1
: 1;
echo $_SESSION['x'];

Related

POST array data in php

I'm trying to post array data to another php, but it doesn't work..
here is my code below.
in func.php
function search($x, $y)
{
...
$martx = array();
$marty = array();
foreach($load_string->channel as $channel) {
foreach($channel->item as $item) {
array_push($martx, $item->mapx);
array_push($marty, $item->mapy);
}
}
echo"<form method=post action='map.php'>";
for($i = 0; $i < 8; $i++)
{
//echo $martx[$i]."<br/>";
//echo $marty[$i]."<br/>";
echo "<input type='hidden' name='martx[]' value='".$martx[$i]."'>";
echo "<input type='hidden' name='marty[]' value='".$marty[$i]."'>";
}
echo "</form>";
header("location: map.php?x=$x&y=$y");
}
martx and marty have data from parsed xml $load_string
And I want to post these data to map.php by form with POST. So, I expect that I can use two arrays martx and marty in map.php like $_POST[martx][0]..
But when I run this code, page remains in func.php, instead of redirecting to map.php
Am I make some mistake?
Thanks in advance.
========================================================================
Thank you all for your kind concern and helpful advice!
I edit my code with your advice,
I delete all echo with using javascript
And I add submit code
here is my code below
....
$martx = array();
$marty = array();
foreach($load_string->channel as $channel) {
foreach($channel->item as $item) {
array_push($martx, $item->mapx);
array_push($marty, $item->mapy);
}
}
?>
<form method='post' action='map.php?x=<?=$x?>&y=<?=$y?>' id='market'>
<script language="javascript">
for(i = 0; i < 8; i++)
{
document.write('<input type="hidden" name="martx[]" value="<?=$martx[i]?>">');
document.write('<input type="hidden" name="marty[]" value="<?=$marty[i]?>">');
}
document.getElementById('market').submit();
</script>
</form>
<?php
//header("location: map.php?x=$x&y=$y");
}
With this code, page redirect to map.php successfully.
But I can't get data like $_POST['martx'][i] in map.php
I think document.write line cause problem
when I write code like
document.write('<input type="hidden" name="martx[]" value="$martx[i]">');
result of $_POST['martx'][i] is "$martx[i]"
Is any error in this code?
I want to use POST method but if I can't post data with POST,
then I'll use session-method as #Amit Ray and #weigreen suggested.
thanks again for your concern.
First, You try to use header('location: xxx') to redirect user to another page.
As the result, you are not submitting the form, so you won't get data like $_POST[martx][0] as you expect.
Maybe you should try using session.
I can see some errors that you are making when you are doing header redirect. There should be no output before you call header redirect but you are doing echo before redirect.
use session to tackle this issue
function search($x, $y)
{
...
$martx = array();
$marty = array();
foreach($load_string->channel as $channel) {
foreach($channel->item as $item) {
array_push($martx, $item->mapx);
array_push($marty, $item->mapy);
}
}
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$_SESSION["martx"] = $martx;
$_SESSION["marty"] = $marty;
header("location: map.php"); exit;
then in map.php you can retrieve the session variables
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$martx = $_SESSION["martx"];
$marty = $_SESSION["marty"];
Then you can use a for loop or foreach loop to iterate through the values

storing incremented value in session variable and printing it

Had googled this but maybe I'm not a good googler. My ultimate goal is to have a view more button that will read the next 6 files from a directory but before I do that I need to figure out this problem:
at the top of my index.php i have this:
<?php
if(session_id() == '') {
session_start();
$_SESSION["count"] = 0;
}
?>
lower down I have this:
<?php
function album() {
$_SESSION["count"]=$_SESSION["count"]+10;
echo $_SESSION["count"];
}
?>
when the user clicks a button its supposed to print the session variable + 10 on each click.. so 10 20 30 40 ..ect. But it keeps printing 10, it's not updating.
Always start session at the top of the page like
<?php
session_start();
if(session_id() == '') {
$_SESSION["count"] = 0;
}
function album() {
$_SESSION["count"] += 10;
echo $_SESSION["count"];
}
?>
You need to first do session_start() and then ask for $_SESSION.
<?php
session_start();
if(empty($_SESSION['count'])){
$_SESSION["count"] = 0;
}
function album() {
$_SESSION["count"] = $_SESSION["count"] + 10;
echo 'Count: '.$_SESSION["count"];
}
album();
?>
This I just tested it and it works fine.

How to echo alternatively 2 values on every refresh?

I'm writing PHP code and I have two variables $var1 and $var2. I want a method that helps me to display alternatively on every refresh one of the two values.
For example:
On the first load of page it must display: echo $var1
On the first refresh of page it must display: echo $var2
On the second refresh of page it must display: echo $var1
On the third refresh of page it must display: echo $var2
etc...
For example you can use sessions.
<?php
session_start();
$a = 1;
$b = 2;
if(!isset($_SESSION['variable'])){
$_SESSION['variable'] = true;
}
if($_SESSION['variable']){
echo $a;
}else{
echo $b;
}
$_SESSION['variable'] = !$_SESSION['variable'];
?>
Counting reloads and saving counter to session (https://github.com/Waldz/Examples/blob/master/session/session_counter.php)
<?php
session_start();
if (!isset($_SESSION['timesPageReloaded'])) {
$_SESSION['timesPageReloaded'] = 1;
}
if ($_SESSION['timesPageReloaded']%2 == 1) {
echo 'VAR1 (odd reload)';
} else {
echo 'VAR2 (even reload)';
}
$_SESSION['timesPageReloaded']++;

Session Variables are Null

I've searched and tried over a dozen suggestions from similar issues on this site, but only a little closer to resoluton.
I am starting out with HTML & PHP so this is a very simplistic couple of scripts.
I am setting up an array with math questions (to test my 9 year old son).
The first script "mathtest.php" sets up the array and sets a couple of variables in the $_session global variable and then a form submits an answer to the question to "mathtest1.php".
My $_session variables are lost when I get to "mathtest1.php".
Please help. I know I can do something with cookies, but I really want to advance in my understanding of sessions.
Here's the 2 scripts:
"mathtest.php":
<?php
session_start();
?>
<html>
<title>Math Test</title>
<head>Math Test</head>
<body>
<?php
$arrayindex = 0;
for ($L = 1; $L <= 12; $L++) {
for ($R = 12; $R >= 1; $R--) {
$setupquestions[$arrayindex] = $L.'*'.$R;
$arrayindex++;
}
}
$_session["questions"] = $setupquestions;
$_session["randomkey"] = array_rand($_session["questions"],1);
?>
<form action="mathtest1.php" method="post">
What is <?php echo $_session["questions"][$_session["randomkey"]]." ?" ?>
<input type="text" name="answer">
<input type="submit" name = "submit">
</form>
</body>
</html>
The script above works as expected, but the script below has null values for the session variables I"m trying to access and use.
"mathtest1.php":
<?php
session_start();
?>
<html>
<body>
<?php
if(isset($_POST['submit']))
{
$answer = $_POST['answer'];
$result = eval("return $_session[questions]$_session[randomkey];");
echo "result = ".$result."<br />";
if ($answer == $result) {
echo "Correct!!";
}
else {
echo "WRONG!!";
}
}
$_session["randomkey"] = array_rand($_session["questions"],1);
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
What is <?php echo $_session["questions"][$_session["randomkey"]]." ?" ?>
<input type="text" name="answer">
<input type="submit" name = "submit">
</form>
</body>
</html>
Other details:
OS X, Chrome Browser, latest version of PHP
XAMPP installation & scripts are on the same laptop as XAMPP, not on an external server.
session cookies are ON
...Trans_ID is ON
I have read & write access to the session save path.
$_SESSION should be in uppercase.
try uppercase!
http://php.net/manual/en/reserved.variables.session.php
$_SESSION
Unlike function names...
function bar(){
}
function Bar(){
}
...
Fatal error: Cannot redeclare Bar() (previously declared in C:\tmp\test.php:3) in C:\tmp\test.php on line 7
... variable names are case-sensitive in PHP:
$foo = 1;
$Foo = 2;
$FOO = 3;
var_dump($foo, $Foo, $FOO);
...
int(1)
int(2)
int(3)
This applies to predefined variables as well, including $_SESSION.

My $_SESSION variable will not hold its value. Any Ideas on why?

I want it to increment and decrement the value in $_SESSION['selection'].
Mousedown on next form results in: "The session is 1".
Mousedown on previous form results in "The session is -1".
Here is the code:
<?php
if (isset($_POST['next'])) {
displaynext();
}
else if (isset($_POST['previous'])) {
displayprevious();
}
else {
session_start();
echo "session started";
$_SESSION['selection'] = 1;
}
function displaynext() {
$_SESSION['selection'] = $_SESSION['selection'] + 1;
echo "The session is $_SESSION[selection]";
}
function displayprevious() {
if ($_SESSION['selection'] != 1) {
$_SESSION['selection'] = $_SESSION['selection'] - 1;
}
echo "The session is $_SESSION[selection]";
}
?>
<form action="<?=$_SERVER['PHP_SELF'];?>" method="post">
<input type="submit" name="previous" value="Previous">
</form>
<form action="<?=$_SERVER['PHP_SELF'];?>" method="post">
<input type="submit" name="next" value="Next">
</form>
Put the session_start() call on the beginning of your file; right after the <?php open tag. You also need to do that on every script that you plan to use sessions.
By the way, instead of writing:
$_SESSION['selection'] = $_SESSION['selection']-1;
$_SESSION['selection'] = $_SESSION['selection']+1;
You can use
$_SESSION['selection']--;
$_SESSION['selection']++;
Read: Increment/Decrement operators
Make sure you're using session_start() on every page you use your session on.
Put the session_start call to the beginning of your code, outside of any conditions.
session_start needs to be called in every script you're using the session in, not just at the very beginning (ie. the first pageload).
You're not calling session_start when moving between pages. Move the call to before the if statements, like this:
session_start();
if(isset($_POST['next'])) {
displaynext();
} else if(isset($_POST['previous'])) {
displayprevious();
} else {
echo "session started";
$_SESSION['selection'] = 1;
}

Categories