Can't call array record in second page PHP - php

I've two page , first page there's an array data and second page I want call array data
Like this
First page index.php
$array_data[]=$array_tmp;
print_r($array_data); // array can display in this page
$_SESSION['one'] = $array_data;
Second page next.php
I want to call array from first page
session_start();
$array = $_SESSION['one'];
foreach( $array as $key => $value ) {
echo $value;
}
print_r($_SESSION['one'])
May I know what's wrong? As array can't display in second page.

I think you should change this code $array = $_SESSION['one']; to $array[] = $_SESSION['one'];. I`m not sure & not tested as well but I think so. Hope this will help.

You need to start the session if you already have not. Without starting the session, you can't assign value to the session variable. So the first code snippet would be like this:
session_start();
$array_data[]=$array_tmp;
print_r($array_data); // array can display in this page
$_SESSION['one'] = $array_data;
Second snippet looks fine but the last line is missing a semicolon. It might sound silly, but that can prevent the whole script from running. Here's the code fixed.
session_start();
$array = $_SESSION['one'];
foreach( $array as $key => $value ) {
echo $value;
}
print_r($_SESSION['one']);
Post more code if this does not work.

Related

Save values to an array permanently?

Is there a way to store values that I append to an array for further cases?
For example, I create an array in one page of php and from another page I append value to the array on the first page. The problem appears when the second page tries to append another value to first page and the value gets replaced. I shall explain with code.
FirstPage.php
<?php
global $file;
print_r ($file);
?>
SecondPage.php
<?php
$file = array();
$id=$_GET['id'];
array_push($file, "$id"); //ID = 1 here
include('FirstPage.php');
?>
When I execute the SecondPage.php, the output is
Array ( [0] => 1)
Then I change the value of ID = 2, the output then is
Array ( [0] => 2)
So the values never get stored in FirstPage.php, they always get replaced.
You can use session variable for this by assigning the value to the session variable on the first page as
SESSION
First Page
<?php
session_start();
$_SESSION['variable'] = $file; //variable assigned the value of array()
print_r ($file);
?>
And on the second page assign the value session variable to the simple variable.
Second Page
<?php
session_start();
$file = $_SESSION['variable'];
$id=$_GET['id'];
array_push($file, $id); //ID = 1 here
?>
And after this you don't need to include first page in again.
As you have not mentioned your array() in the question take this as an example
First.php
<?php
session_start();
$file = $_SESSION['varname'];
print_r($file);
?>
Second.php
<?php
session_start();
$file = array(1,2,3,4);
array_push($file,'5');
$_SESSION['varname'] = $file;
header("Location: first.php");
?>
You should use database, save your array to file or use another method of storing data. These operations you are using are stateless. Content of arrays will not be saved between next executions of PHP scripts.
Sessions work until browser closing so it's not also the solution of your problem.

Array_push pushes invisible element, and only works on second push

I had a problem with my array_push, that i noticed.
So what i'm doing.:
I have a site, where there are some buttons with a specific value.
Each value is getting fetched from a database.
I have a session called test, that get's converted to an array(to store multiple in the same array)
Everytime one of the buttons are clicked, the value for that specific button, is getting pushed to the array.
But, i can ONLY see that it has been pushed at the second try.
[test] => Array( [0] => 21304 )
This is what i see, after second try. But my array count, says that there are 2 elements, in that array.
Here is my code:
if(isset($_POST['process'])) {
if(!isset($_SESSION['test'])) {
$_SESSION['test'] = array();
$array_merge = array_push($_SESSION['test'], $_POST['process']);
}
}
The $_POST['process'] is the button with the unique value.
Can somebody maybe see what I'm doing wrong here?
Kind regards
You are only adding to the $_SESSION['test'] array if $_SESSION['test'] was not previously set.
So you need to always add an occurance to the session array and only initialise the session array if it was not previously set
session_start();
// ...
if(isset($_POST['process'])) {
if(!isset($_SESSION['test'])) {
$_SESSION['test'] = array();
}
$_SESSION['test'][] = $_POST['process'];
}
NOTE from the manual
If you use array_push() to add one element to the array, it's better to use $array[] = because in that way there is no overhead of calling a function.

Array index increment

I have this array in php code. I want to have that whenever page is being called it should print value of first array index and when next time second value of array index and so on... what modification I could do? for now it´s printing everything when being called single time.
<html>
<?php
$addresses = array('ifcbxespra', 'ifcheqjbmea', 'ifcqiknsa', 'ifcqirtjla', 'ifcwqsrlmn', 'ifclmkmzhz','ifcwdujhgc','ifcihddngh','icffhzudcd','ifchnsqzgs','ifcgssqrhg');
foreach ($addresses as &$value) {
echo $value ;
}
?>
</html>
I'm not sure if I understood what you want. But if you want to print the first array's value when the page loads one time, the second array's value when the page loads another time and so on, you can do this:
<?php
if(!isset($addresses) || empty($addresses)){ //checks if the array is not initialized or if it's empty
$addresses = array('ifcbxespra', 'ifcheqjbmea', 'ifcqiknsa', 'ifcqirtjla', 'ifcwqsrlmn', 'ifclmkmzhz','ifcwdujhgc','ifcihddngh','icffhzudcd','ifchnsqzgs','ifcgssqrhg');
echo $addresses[0]; //print the first value
array_splice($addresses, 0, 1); //removes the first element of the array and reindexes it
}else{
echo $addresses[0]; //print the first value
array_splice($addresses, 0, 1); //removes the first element of the array and reindexes it
}
The logic behinds it is: if the array already exists and is not empty (it has values), print the first value and then remove it, so next time the first value will be the second actual value. When the array is empty, redefine it as to start again.
You can search for more information on array_splice() here.
P.S.: you have to use PHP's $_SESSION to save the array between the pages.
You can use something like $_SESSION and store there the last index.
For example:
$array = array('one', 'two', 'three');
if (!$_SESSION['nextIndex'] || $_SESSION['nextIndex'] >= count($array)) {
$_SESSION['nextIndex'] = 0
}
// print the value
echo $array[$_SESSION['nextIndex']];
// increment the nextIndex
$_SESSION['nextIndex']++;
NOTE: This will only work for the same user. Each page reload will increment the array index. But if you need some cross-user counting, then you have to store the information somewhere on the server, like a DB or even a simple txt file.
Check out this example: http://hibbard.eu/how-to-make-a-simple-visitor-counter-using-php/
Finally I solved this problem with the MySQL. created a column with all code. and then call the script every-time when user press button. In the script first I fetch first raw and print that value, and then, delete that raw. so every-time user will get unique value from the list of code And it is working fine.

session does not keep the values

I have an array of variables and I need to show its values.
So at first I send "me" variable to copy the array into session then I send "mypage" variable to show the first variable of the array but when I send "mypage" variable it seems the session is empty as show function does not show anything.
Please advice if you think I should use any other method as I am doing this to implement pagination.
<?php session_start();
if(isset($_GET["me"]) //if me variable is received copy the array in session
{
$myarray = array("foo", "bar", "hallo", "world");
$_SESSION["mysession"] = $myarray;
}
if(isset($_GET["mypage"]) // if mypage variable is received go to show function
show()
show() // show value 1 of the session
{
$values = array();
$values= $_SESSION['mysession'];
echo $values[1];
}
?>
Your code is very vague though for your question it seems that you are accessing SESSION with wrong key.
As you are setting session with mysession key above. Try to change below in your show function,
$values= $_SESSION['mysession'];

How to add visited pages urls into a session array?

Everytime the user visit a page, the page url will be stored into an array session. I want to have 10 elements in the array only. So that 10 elements will save 10 latest visited page urls. Here is my codes :
<?php
$currentpageurl = $_GET['username'];
$urlarray=array();
$urlarray[] = $currentpageurl;
$_SESSION['pageurl']=$urlarray;
foreach($_SESSION['pageurl'] as $key=>$value)
{
echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
}
?>
I tested the code, it always overwrite the element in the array with new visited page, thus it has only 1 element in the array. How to make it not to overwrite the element?
You are always overwriting the array with a new one here:
$urlarray=array(); // new empty array
$urlarray[] = $currentpageurl;
$_SESSION['pageurl']=$urlarray;
Instead use:
session_start();
// like #Kwpolska said, you probably miss that, so $_SESSION didnt work
is_array($_SESSION["pageurl"]) or $_SESSION["pageurl"] = array();
// fix for your current problem
$_SESSION['pageurl'][] = $currentpageurl;
// This appends it right onto an array.
$_SESSION["pageurl"] = array_slice($_SESSION["pageurl"], -10);
// to cut it down to the last 10 elements
Simplest way to do this and keep just the last 10 entries will be to create your initial array with the correct size (via array_fill()). Then we can push new items onto the beginning of the array and pop old items off the other end using array_unshift() and array_pop().
session_start();
// Initialise URL array with 10 entries.
if (empty($_SESSION['pageurls'])) {
$_SESSION['pageurls'] = array_fill(0,10,'');
}
function trackPage($url) {
array_unshift($_SESSION['pageurls'],$url);
array_pop($_SESSION['pageurls']);
}
Make sure the above code always runs first. Then you can pass new URLs to the array when you want. So, perhaps something like:
trackPage($_SERVER['REQUEST_URI']);
You've ommitted session_start();. Working code (without trimming):
<?php
session_start();
$currentpageurl = $_GET['username'];
$_SESSION['pageurl'][] = $currentpageurl;
foreach($_SESSION['pageurl'] as $key=>$value) {
echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
}
?>

Categories