I'm sending data over to a PHP file and storing it using $_SESSION. I'd like to post multiple instances of data to the session at different times and view these on the front end. Currently I can store one item in my session and this is displayed on the front end, however I'm struggling to add further instances of artist and title as it simply gets overwritten every time I $_POST data across.
How do I store and display an array of $_POST data in the session variable? I've tried adding a further set of [] after $_SESSION['artist'] and $_SESSION['title'] but this doesn't work.
<?php
session_start();
if(isset($_POST['artist']))
{
$_SESSION['artist'] = $_POST['artist'];
}
if(isset($_POST['title']))
{
$_SESSION['title'] = $_POST['title'];
}
print_r($_SESSION['artist']);
echo "<br>";
print_r($_SESSION['title']);
?>
You'll need to use an array to hold these values, so $array[] = $value will append $value to the $array.
Example:
if(isset($_POST['title'])) {
// Append POST data to SESSION
$_SESSION['titles'][] = $_POST['title'];
}
print_r($_SESSION['titles']);
You don't need to make sure $array is actually an array, since [] will make the variable an array if needed: Note: array_push() will raise a warning if the first argument is not an array. This differs from the $var[] behaviour where a new array is created.
<?php
session_start();
if(isset($_POST['artist']))
{
$_SESSION['artist'][] = $_POST['artist'];
}
if(isset($_POST['title']))
{
$_SESSION['title'][] = $_POST['title'];
}
print_r($_SESSION['artist']);
echo "<br>";
print_r($_SESSION['title']);
?>
user array to store it.
Related
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.
I want to add an element to PHP array when form is submitted and then add that array to $_SESSION so I can display it on other page while $_SESSION is active, but when an element is added to an array, element that is already in it is deleted so I constantly have 1 item in array. Any suggestions?
Here's the code:
$korpa = array();
$_SESSION["korpa"] = $korpa;
if(isset($_POST["add"])){
array_push($korpa, $_POST["id"]);
}
You keep assigning an empty array to your session variable, so it will be empty at the start of your script, before you append the POST variable.
Instead, you can append directly to that session variable if the condition is met.
// Initialize the session array if its not set
if (!isset($_SESSION["korpa"])) {
$_SESSION["korpa"] = [];
}
// Then append the POST value to the session if that's set
if (isset($_POST["add"])) {
$_SESSION["korpa"][] = $_POST["add"];
}
Naturally you will need to call session_start() at the top of every page using sessions, otherwise they will not be set across your different pages.
I have a problem storing session value;
I am not able to increment the session count variable
via the AJAX Jquery call with some value passing
to function, also my previously set array which stores the session is change with a new one.
What is the problem here:
1>when i use one controller function
startOnlineTest($testid=0)
i set session countnew as 0
$this->session->set_userdata('countnew',0);
and in view i use jquery to pass data to other function of same controller
public function ResponseOnline($qid,$response)
using change effect of jquery
echo "[removed]$(document).ready(function(){";
foreach($question['childQuestion'] as $q=>$aq){ //
echo "\$(\"input:radio[name=qid-$q]\").live('change',function(){
var sr=\$(\"input:radio[name=qid-$q]:checked\").map(function() {
return $(this).val();
}).get().join();
var qid = \$(\"input:radio[name=qid-$q]\").attr(\"qaid\");
"; echo "\$.get('"; echo base_url();echo "testpapers/ResponseOnline/'+qid+'/'+sr,{},function(data)
{\$('#res').html(data)});
});";}
echo"});[removed]" ;// this script is working fine
now the problem is this i get the session value overwrite by the current one although i
use array my code for ResponseOnline
is
public function ResponseOnline($qid,$response)
{
echo "this" .$this->session->userdata('countnew'); // this is not echo as set above by function startOnlineTest($testid=0)[/color]
i set session countnew as
$this->session->set_userdata('countnew',0)
echo $d=$qid; // i know its no use but to save time as tested on $d
$s=$response;
if($this->session->userdata('countnew')==0) // algo for this function i check the
//countnew session varaible if 0 do this
{
$sc=$this->session->userdata('countnew'); // store the countnew variable
echo $sc=$sc+1; // increment the counter variable
$this->session->set_userdata('countnew',$sc); // store it in session
echo "this is incrementes session value";
echo $this->session->userdata('countnew');
$r2[$d]=$s; // store array value $r2 with key $d and value $s
$this->session->set_userdata('res',$r2); //set this array value in session
}
else{ // if session countnew!=0 then do this
$r2=$this->session->userdata('res'); // first store $r2 as array return from session
$r2[$d]=$s; //then add value to this array
$this->session->set_userdata('res',$r2); // storing this array to session
}
echo '<pre>';
print_r($r2); // printing the array
}
i get the result for say for first call is fine but for second call my value is overwrite session show Array([32323]=>23)) if i pass function (32323,23) if i pass (33,42)
i get Array([33]=>42) my old value is destroyed.
You should just probably use regular sessions in php because sessions in codeigniter will only allow you to store a single item.
Something like this:
$_SESSION['item'][] = $array;
Or maybe you could still use CodeIgniter sessions by doing something like this:
$items = $this->session->userdata('items');
array_push($items, $new_item);
$this->session->set_userdata('items', $items);
If you want to define the keys as well:
$items = $this->session->userdata('items');
$items['your_key'] = $new_item;
$this->session->set_userdata('items', $items);
I need to update a json list of object via url post data. For example, with url:
http://myweb.com/index.php?name=Peter&surname=Brown
in php, using get method:
$name = $_GET["name"];
$surname = $_GET["surname"];
$json = array();
$json["nombre"] = $name;
$json["lat"] = $lat;
$data[] = $json;
$json_end= json_encode($data);
and json_end efectively is done like I want:
[{"name":"Peter","surname":"Brown"}]
My question is about how I can do it incrementing the json, in order to build an array like:
[{"name":"Peter","surname":"Brown"}]
[{"name":"newname","surname":"newsurname"}]
// and so on
each time user use the url with new parameters.
Do I need to write to a file, or to database? Any tips will be apreciated.
The idea is to be able that any user can add some dat using url. I tried to store the json to a fiel but the storing is durable only along the current session.
<?
/* This needs to be at the top of your file, without ANYTHING above it */
session_start();
/* ... */
if(!array_key_exists('entries', $_SESSION))
{
$_SESSION['entries'] = array();
}
$_SESSION['entries'][] = array("name" => $_GET["name"], "surname" => $_GET["surname"]);
$json_string = json_encode($_SESSION['entries']);
This would produce a single JSON. However I don't know whether you meant to or not, but your output is a series of separate JSONs. You could do this by replacing the last line above with:
$json_string = '';
foreach($_SESSION['entries'] as $entry){
$json_string.= json_encode($entry) . "\n";
}
You would also probably want a way to reset/empty the array. In which case I'd change the if test from:
if(!array_key_exists('entries', $_SESSION))
to:
if(!array_key_exists('entries', $_SESSION) || array_key_exists('reset', $_GET))
Which you could use by visiting
http://myweb.com/index.php?reset
Edit: If somewhere you add the following code:
foreach($_SESSION['entries'] as $id=>$entry){
printf("%2d: %s\n", $id, json_encode($entry));
}
You'll get a list of the json elements enumerated by their respective keys. For example, it might look like:
0: "[{\"name\":\"Peter\",\"surname\":\"Brown\"}]"
1: "[{\"name\":\"newname\",\"surname\":\"newsurname\"}]"
2: "[{\"name\":\"George\",\"surname\":\"Washington\"}]"
3: "[{\"name\":\"John\",\"surname\":\"Adams\"}]"
If you then add the following code:
if(array_key_exists('del', $_GET) && is_numeric($_GET['del']))
{
$key = (int)$_GET['del'];
if(array_key_exists($key, $_SESSION['entries']))
{
unset($_SESSION['entries'][$key]);
}
else
{
printf('<strong>ERROR: $_GET['del'] = %d but $_SESSION['entries'][%d] doesn't exist.</strong>', $key, $key);
}
}
you'll be able to delete individual json entries by specifying id as the del GET parameter.
For example,
http://myweb.com/index.php?del=2
would delete the entry corresponding to '[{"name":"George","surname":"Washington"}]';
And the remaining entries would be:
0: "[{\"name\":\"Peter\",\"surname\":\"Brown\"}]"
1: "[{\"name\":\"newname\",\"surname\":\"newsurname\"}]"
3: "[{\"name\":\"John\",\"surname\":\"Adams\"}]"
4: "[{\"name\":\"Thomas\",\"surname\":\"Jefferson\"}]"
Just make a nested array of users:
$data = array (
0 => array("name"=>"Peter","surname"=>"Brown"),
1 => array("name"=>"newname","surname"=>"newsurname")
);
echo json_encode($data);
// [{"name":"Peter","surname":"Brown"},{"name":"newname","surname":"newsurname"}]
I think it would be easiest to store the data in a session, something like this:
<?php
session_start();
if (isset($_GET['name'])) {
$_SESSION['json'][] = $_GET;
}
echo json_encode($_SESSION['json']);
?>
Edit: You may want to filter the $_GET array before storing it in the session so that you don't store values that aren't meant to be stored.
Edit: Of course, if you want to save this data for more than one session you would need to use files or a database (or perhaps a cookie). It all depends on what you want to do with the information.
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 />';
}
?>