Reputation: 458
PHP can't maintain the state lets say the variables initialize in one process will be lost if the page gets reload i was reading the some of the answers on Stack over flow but unfortunately i couldn't get much out of them , what i know is in order to maintain the state i need to use Session i have very simple script for learning how session works
index.php
<?php
if ( !isset($_SESSION['id']) ){
session_start();
$_SESSION['id'] = 1;
echo "Session started at index.php and id is =";
echo $_SESSION['id'];
}
else {
++$_SESSION['id'];
echo "The session id is : ".$_SESSION['id'];
}
?>
<br>
<a href="index.php">Index.php</a>
But whenever i reload the Page i get the following message
**Session started at index.php and id is =1**
Can you please tell me what i am doing wrong how can i maintain state using Sessions? what i eventually want to do is store a object in Session variable on every post i want to append data in a instance variable (array) of that object
Upvotes: 0
Views: 1434
Reputation: 1680
The problem is that on the first load you are checking for a session, which by default does not exist until you start one, and then subsequently starting a session and setting the ID to 1. from that point beyond it will be "1". Also .. you need a session start each time you load so you will need in the IF and the ELSE.
<?php
if (!$_SESSION){
session_start();
$_SESSION['id'] = 1;
echo "Session has been initiated at index.php and id is =". $_SESSION['id'];
} else {
session_start();
$_SESSION['id']++;
echo "The session id is : ".$_SESSION['id'];
}
?>
<br>
<a href="index.php">Index.php</a>
Now for some reason.. if you had a previous session and linked to index the ID would still increment and not be "reset" by hitting index.
to inject submitted form variables into your session, just set the variables manually:
<?PHP
if (isset($_POST['myVariable']) && !empty($_POST['myVariable'])) {
$_SESSION['myVariable'] = $_POST['myVariable'];
}
?>
but each time you submit the form with the same variables, they will be overwritten
Upvotes: 1
Reputation: 427
Put
session_start();
under
<?php
you need to declare the session before referencing it
As you can see from your code you are saying if isn't set, well its not going to know as you haven't started the session.
Upvotes: 0