I have multiple pages. On each page I have a list of items. So on Page 1, I have Items 1-10. On page 2, I have items 11-20. It is NOT ten items per page but the point is that page 3 should start off with the number immediately following the last number on page 2.
The pages have a simple numeric variable so the counting of items works fine per page but I want it to be set in one place.
I am brand new to php so my question is mostly about how and where to store a variable that would keep track of this item count over multiple files?
Desired behavior:
Let's say Page 1 has 5 items and my counter variable on page 1 sets them to be correctly numbered to:
1.apple
2.grape
3.pear
4.banana
5.orange
But let's say I need to remove banana. When I do so, the current counter on page 1 works fine and sets to:
1.apple
2.grape
3.pear
4.orange
But on page 2 the counter variable is set to 6 and has:
6.mango
7.peach
8.watermelon
I want to set the persistent variable so that when I remove a fruit, it will update not only the current page the removed fruit is on but every page after that. So it would adjust page 2 to:
5.mango
6.peach
7.watermelon
Would sessions make that change permanent or would it disappear with the user's cookie?
<?php
//On the first line of your PHP code
session_start();
//then store your variable in the SESSION array.
$_SESSION['yourCountersNameHere'] = 56;
//You should now have acces to its value from page to page like this
echo $_SESSION['yourCountersNameHere'];
//Should display 56.
?>
you could also store it in a DB. and then check in the DB on every page.
//to connecte
$m_DB = new PDO("mysql:host=".$Host.";dbname=".$DBName."; charset=utf8", $Login, $Password);
//check value in DB
$query = "SELECT * FROM table";
$stmt = $m_DB->prepare($query);
//$param here is empty but normaly it would be a array for all your params like this:
//$param = array('rowname'=>$value, 'rowName2'=>$value2, .........and so on for all the $params you use.);
$getCounter = $stmt->execute($param);
while($Counter = $getCounter->fetch())
{
//Display the value in your MySQLDB.
echo $Counter['table.rowName'];
}
If you use another DB type than MYSQL the code should be fairly the same exepte for a couple of changes you'll have to make.
You can look at http://www.php.net/manual/en/session.examples.basic.php for more information using sessions.
Any variable that is placed in a session will be persistent for the user as long as their cookie doesn't expire.
On each page of your site that will access/change your page variable, add this code at the very beginning:
<?php
//On the very first line of each file using the variable
session_start();
Then for accessing/setting see the following:
<?php
session_start();
// store session data
$_SESSION['views']=1;
?>
<html>
<body>
<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
</body>
</html>
This code will spit out one from the session variable 'views'
To check if something has been set:
<?php
session_start();
if(isset($_SESSION['views']))
//do something
Clearing out the session variables:
<?php
session_start();
if(isset($_SESSION['views']))
unset($_SESSION['views']);
?>
Deleting the session:
<?php
session_destroy();
?>
Best site in the universe : http://www.w3schools.com/php/php_sessions.asp
Related
I want do store multiple values each time page is loaded. But my session array is not working, it's acting like a simple array.
session_start();
...some code...
$_SESSION['a'] = $input_value;
print_r($_SESSION); //here I have only 1 variable
Your not creating an array, try the code below
$_SESSION['a'][] = $input_value;
I'm able to pass a variable from a link on my first page to the 2nd page, but i'm having a hard time passing that variable into the third page. How can i pass the variable to the third page?
First Page is a HTML Page
Go to Page Two
Second Page is a PHP Page
<?php
echo $_GET["Page"];
?>
Third Page is a PHP Page
???
To pass a variable along from one page to another you can choose from multiple options:
Sessions
Cookies
Storage (File or Database)
Sessions
The first page:
<?php
// Prepare to use sessions (This should be at the top of your page)
session_start();
if (!isset($_SESSION['test']) && isset($_GET['test'])) {
$_SESSION['test'] = $_GET['test'];
header("Location: secondpage.php");
exit;
}
The second page:
<?php
session_start();
// Output session
var_dump($_SESSION['test']);
Cookies
First page:
<?php
if (isset($_GET['test'])) {
setcookie('test', $_GET['test'], time() + (86400 * 30), "/");
}
Second page:
";
echo "Value is: " . $_COOKIE['test'];
}
Files and Databases
This is too big a subject to discuss in one answer. However, there are tons of tutiroals that can learn you all you need to know about PHP and MySQL.
Example
First page:
Go
Second page:
<?php
session_start();
if (isset($_GET['page'])) {
$_SESSION['page'] = $_GET['page'];
}
header("Location: page_three.php");
exit;
?>
Third page:
<?php
session_start();
// Will echo two
echo $_SESSION['page'];
?>
Resources
PHP - Sessions
PHP - Cookies
You have two main options:
you can keep linking the pages with url parameters
Go to Page Two
Go to Page Three
This solutions is quite inconvenient if you want to keep the "page" value for a long term
The best solution as user1234 said is to store the value in the session.
if your first page MUST be html and you can't store it at begining you can do in any of your php pages
$_SESSION['Page'] = $_GET["Page"];
Here is my scenario.
I have 2 different pages with php
1). index.php page have session name declared as "session_one"
$some_session = session_name("session_one");
session_set_cookie_params(0, '/', '.domain.net');
session_start();
2). order.php page have session name declared as "sesson_random" (this is required to have another session name due to nature of implementation
$some_session = session_name("sesson_random");
session_set_cookie_params(0, '/', '.domain.net');
session_start();
now the issue that I am facing is that I have stored some values on index.php in session which I want to retrieve on order.php. I have tried many ways but unable to pass it.
Please note that I can not pass those values in query string of url.
Please help
You should be able to read the data from the other session, by restoring it before you open the new one. All you have to do is use the session_id function. I tested it with this code right here: (index.php)
<?php
session_name("session_one");
session_start();
$_SESSION["test"] = array("this is just a test");
print_r($_SESSION);
?>
Now, all you have to do is load the other session first and save the values into an array: (order.php)
<?php
if(isset($_COOKIE["session_one"])){
session_id($_COOKIE["session_one"]);
session_name("session_one");
}else{
session_name("session_one");
}
session_start();
$session = $_SESSION;
session_write_close();
print_r($session);
if(isset($_COOKIE["session_random"])){
session_id($_COOKIE["session_random"]);
session_name("session_random");
}else{
session_name("session_random");
}
session_start();
$_SESSION["other"] = array("this is another test");
print_r($_SESSION);
?>
The two sessions get combined. If you are not bothered by that, you should be good to go. Got some inspiration from here:
Can multiple independent $_SESSIONs be used in a single PHP script?
I am trying to make a login form with PHP, and I want to get a value from a form like so:
$name = $_POST["name"];
$email = $_POST["email"];
then, when the user clicks "Submit", I want the new page to have access to these variables. Using the
include 'file1.php';
technically works, but I dont want ALL of 'file1.php', just the variables.
Any Suggestions?
You have to use session. Here is a simple demonstration:
page1.php - Load page one to set the session variable
<?php
// begin the session
session_start();
// set the value of the session variable 'foo'
$_SESSION['foo']='bar';
// echo a little message to say it is done
echo 'Setting value of foo';
?>
page2.php - Load page two and it will have access to the session variable you set in page1.php
<?php
// begin our session
session_start();
// echo the session variable
echo 'The value of foo is '.$_SESSION['foo'];
?>
This is exactly what sessions are for.
Sessions are a simple way to store data for individual users against a unique session ID. This can be used to persist state information between page requests. Session IDs are normally sent to the browser via session cookies and the ID is used to retrieve existing session data.
I have created a page with name edit.php. I have moved on this page from action.php using a edit button. I have successfully retrieved the values in the respective text boxes and other form items. I have problem that if by mistake this edit.php page is refreshed all values are gone. What is other way to maintain the values? Though thing are going well if page is not refreshed. If session variable is created than how values are retrieved of both that is of session variable and from database?
What I have did with problem.. I have requested "albumid" on action.php page..
session_start();
$aid = mysql_real_escape_string($_REQUEST['albumid']);
Now if action.php page is requested through edit.php page using edit button. than I have created a session variable. and destroyed it after successful update query.
if (isset($_POST["edit"])) {
$_SESSION["aid"]=$aid;
$result= mysql_query("SELECT * FROM table WHERE a_id =".$_SESSION["aid"]) or die(mysql_error());
$row=mysql_fetch_array($result); }
It means now session is created.. if page is refreshed than also session values remains and accordingly values are selected from this variable.
if($_POST['update']!="") {
Update query
session destroyed }
Than also my problem is not solved that is if page is refreshed before hitting update button I am loosing all values.
session variables are just data you put into the $_SESSION superglobal. Accessing them is no different than accessing any other array, except that the session array is saved for you automatically. All you need to remember is to do a session_start() before doing anything with the session.
$_SESSION['formfield1'] = $_POST['formfield1'];
$_SESSION['formfield2'] = $_POST['formfield2'];
etc...
<input type="text" name="formfield1" value="<?php echo htmlspecialchars($_SESSION['formfield1']) ?>" />
By default, PHP uses file-based sessions. To put it into a database, you'd have to write your own session handlers and point PHP to them using session_set_save_handler().
When you submit, save the values in appropriately named $_SESSION members. Then on your page, if you can't find the members in $_GET/$_POST, you can choose to look them up in $_SESSION. Or vice versa. Every time the user submits a form though, you should always update $_SESSION so that the values are the most current. (in case they backtrack, or resubmit, or whatnot).
session_start();
if (!empty($_POST)) {
$_SESSION['post'] = $_POST;
}
elseif (empty($_POST) && !empty($_SESSION['post'])) {
$_POST = $_SESSION['post'];
}
just don't forget to unset($_SESSION['post']); when you're done with it.
If I have understood your question correctly, I think you need some variables from database as well as from the session.
Simply put the key of your database tuple (or keys in case of multiple values) along with other stuff. Page, upon loading will check for the session variables and when it finds the key, it can use it to retrieve the data from the database.
In your previous page, the code will look like this :
$_SESSION["player_key"] = 56;
$_SESSION["tournament_key"] = 100;
And current page, start processing like this :
<?php
session_start();
$player = $_SESSION["player_key"];
$tournament = $_SESSION["tournament_key"];
/*
* your database connection steps
*/
$query = "select * from player where pid=".$player;
$res = mysql_query($query);
/*
Now assign values for your forms/components here or anywhere in the page. You don't have to read anything from the querystring.
*/
?>