Codeigniter add new item to current session userdata array - php

So I have this array:
$data = array(
'item_1' => $this->input->post('item_1'),
'item_2' => $this->input->post('item_2'),
'item_3' => $this->input->post('item_3')
);
$this->session->set_userdata( 'items', $data );
And I want to add a new item to that array, so the updated array of userdata will be like this:
$data = array(
'item_1' => $this->input->post('item_1'),
'item_2' => $this->input->post('item_2'),
'item_3' => $this->input->post('item_3'),
'item_4' => $this->input->post('item_4')
);
$this->session->set_userdata( 'items', $data );
How to do that, Thank you

Follow these steps to add data to the current session:
$data = $this->session->userdata('items');
$data['item_4'] = $this->input->post('item_4');
$this->session->set_userdata('items', $data);
Here, we first take out the current session items in an array, add another item to the array, you can do a array_push() but I prefer the above. Now, set the session back with the updated data.

Got this from ellislab:
Adding Custom Session Data
A useful aspect of the session array is that you can add your own data to it and it will be stored in the user's cookie. Why would you want to do this? Here's one example:
Let's say a particular user logs into your site. Once authenticated, you could add their username and email address to the session cookie, making that data globally available to you without having to run a database query when you need it.
To add your data to the session array involves passing an array containing your new data to this function:
$this->session->set_userdata($array);
Where $array is an associative array containing your new data. Here's an example:
$newdata = array(
'username' => 'johndoe',
'email' => 'johndoe#some-site.com',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
If you want to add userdata one value at a time, set_userdata() also supports this syntax.
$this->session->set_userdata('some_name', 'some_value');
So in essence you should be able to create the item you want to add and then add it to the session by using $this->session->set_userdata("item_4", "item_4"); or $this->session->set_userdata($newdata) if you want to add many items .

Related

session variable keeps overriding in php

In my php code I am trying to collect some data each time a user clicks a particular button. However even though the data is avaiable everytime the button is executed only the latest data is added to the array.
How can I keep adding this new data while keeping the old data
$session_data['items'] = array('id' => $id,'price' => $price);
$this->session->set_userdata($session_data);
edit
Updated code with suggested answer however still no outcome
$session_data['items'][]= array('id' => $id,'price' => $price);
$this->session->set_userdata($session_data);
You can use an 2-dimensional array data type. This way, you can have a lot of data inserted and get the latest value too.
$session_data['items'][] = array('id' => $id, 'price' => $price);
$session_data['items'][] = array('id' => $id, 'price' => $price + 1);
If you keep adding it the above way, it pushes new data to the end. In the above code, both the values are saved.
Use CodeIgnighter's push() method to add to a session variable that contains an array.
$this->session->push('items', array('id' => $id, 'price' => $price));

Obtaining All Cache Keys in Zend-Cache

Here is my cache initialization code:
use Zend\Cache\StorageFactory;
$cache = StorageFactory::factory(array(
'adapter' => array(
'name' => 'filesystem',
// With a namespace we can indicate the same type of items
// -> So we can simple use the db id as cache key
'options' => array(
'namespace' => 'dbtable',
'cache_dir' => Pluto::path('cache')
),
),
'plugins' => array(
// Don't throw exceptions on cache errors
'exception_handler' => array(
'throw_exceptions' => false
),
// We store database rows on filesystem so we need to serialize them
'Serializer'
)
));
What Id like to know is how do I obtain all of the cache keys we have inside this cache object
For example, executing this code now:
$cache->setItem('key1','foo');
$cache->setItem('key2','bar');
$cache->setItem('key3','baz');
And executing this code at a different area/point:
$cache->setItem('key4','foo2');
$cache->setItem('key5','bar2');
$cache->setItem('key6','baz2');
I'd like an array containing ['key1','key2','key3','key4','key5','key6'] which would come presumbly from an internal array of all the keys inside the cache object (including ones that were not affected during this specific request)?
AFAIK, there is no method from zend-cache for retrieving all keys inside cache object. But if you wanna retrieve all keys, you can iterate the object. It is not array, but you can make it as array if you want.
$caches = $cache->getIterator();
$cacheKeys = []
foreach ($caches as $key) {
// $key is the cache key
$cacheKeys[] = $key;
}
print_r($cacheKeys);

Laravel 5.2 - adding to existing session array overwrites existing session

I am attempting to store basket data in a session in Laravel 5 via AJAX but each time I try and push an item to the array stored as the value to 'basket', the existing 'basket' array is overwritten.
Below is my controller method:
public function add(Request $request)
{
$success = false;
if ($request->ajax()) {
$ticket = Ticket::find((int) $request->get('ticket_id'));
if ($ticket) {
if (!$request->session()->has('basket')) {
$request->session()->put('basket', []);
}
$item = [
'attraction.name' => $ticket->attraction->name,
'ticket.quantity' => $request->get('quantity'),
'ticket.price' => $ticket->price,
];
$request->session()->push('basket', [$ticket->id => $item]);
$success = true;
}
}
return response()->json(['success' => $success]);
}
An item is set in the basket session array on the first instance, but I am expecting it to add to this array rather than overwrite when I post more item data over to this method.
The end result I'm looking to achieve is this:
Array
(
[basket] => Array
(
[123] => Array
(
[attraction.name] => Attraction 1
[ticket.quantity] => 2
[ticket.price] => 14.5
)
[456] => Array
(
[attraction.name] => Attraction 2
[ticket.quantity] => 3
[ticket.price] => 12
)
)
)
I've tried using the Session facade equivalent methods, but to no avail :(
Any help would be greatly appreciated. Thanks :)
I had tried array_merge() but again my session was being overwritten. So, after putting my debug hat on yet again, I've found the reason why it was happening.
Session data was not persisting after each request. As my session wasn't being remembered, !$request->session()->has('basket') was always evaluating to true therefore my basket session was being set back to an empty array each time.
I needed to return my request as JSON using the below line in order for my session data to persist. Maybe this is because I have dataType: 'json' as a property in my AJAX call?
return response()->json($request);
I also took your advice and grabbed the basket session array, pushed new data to it and put back into session.
Sorted! Thank you both for your help :)
I experienced a similar issue and discovered that after adding values to the session you need to call
session()->save();

A row associates with session is deleted when user logout in YII

I have a site that uses YII. One thing that it does is storing session information into a MySql database table YiiSession. Also in a separate table (users_sessions), a new row is inserted with the following information:
session id
user id
online status of a user
I create another table for session because YiiSession is part of YII. Also users_session keeps track online status of a user, whereas YiiSession doesn't.
I only make an insertion into users_session during user login.
But I don't understand that when user logs out, the session that associates with the user got deleted.
Note that the session_id in the users_session is a foreign key to the one in YiiSession. But the one in YiiSession still exists even though it has an expiration date.
What mechanism that possibly deletes the row? Please help.
You should extend CDbHttpSession and overwrite the method destroySession($id). There you append the code and delete your entry also.
Configure Yii to use your session class instead of it's own in config/main.php:
'session' => array(
'autoStart' => true,
'class' => 'application.components.<your session class name>',
'connectionID' => 'db',
'sessionTableName' => 'session',
'autoCreateSessionTable' => false,
'timeout' => 3600, // 60 min
),
However I would not do this with a separate table, just add some fields to the YiiSession table. That's what I did and it works pretty well.
EDIT:
You should create a file named MyDbHttpSession.php in protected/components.
In this file extend CDbHttpSession like so:
class MyDbHttpSession extends CDbHttpSession
{
protected function createSessionTable($db, $tableName)
{
// basically this is a copy of CDbHttpSession
$db->createCommand()->createTable($tableName, array(
'id' => 'CHAR(32) PRIMARY KEY',
'expire' => 'integer',
'data' => $blob,
// your additional fields
'idUser' => 'INT(10) NULL',
'online' => 'TINYINT(1)',
// more of your fields here if you have
));
}
// this sets the user ID by session ID
public function setIdUser($idUser)
{
$db = $this->getDbConnection();
$db->setActive(true);
$db->createCommand()->update($this->sessionTableName, array('idUser' => (int) $idUser),
'id=:id', array(':id' => $this->sessionId)
);
}
// and this sets the online status, pass true or false to $online
public function setOnline($online)
{
$db = $this->getDbConnection();
$db->setActive(true);
$db->createCommand()->update($this->sessionTableName, array('online' => (int) $online),
'id=:id', array(':id' => $this->sessionId)
);
}
}
Set Yii to use your session class instead of it's own like I wrote above.
You should already have a class WebUser. If not, create one in protected/components and extend CWebUser.
In this class add a method afterLogin:
public function afterLogin($fromCookie)
{
// store user ID and online status in session table
Yii::app()->session->setIdUser($this->id);
Yii::app()->session->setOnline(true);
return parent::afterLogin($fromCookie);
}
You can from wherever you are in Yii use Yii::app()->session->setOnline(true); or Yii::app()->session->setOnline(false);

How to create an empty field if the field doesn't exist in MongoDB

I have a document that is created on weakly bases (field delimeter hold date) for each user's week.
Every time the user session expires I check to see the user has a document for that particular week (so that all updates dont fail)
I am trying to avoid 2 fetches : 1) a fetch to check if the document exists, 2) create another query that creates or not that document depending on whether it exists already
I was wondering if there is such a function within mongo... Create if doesn't exist otherwise do nothing?
Currently, upsert inserts if it is not there or updates if it is there. Thus, is not a valid solution. I need if ( !exist){ update/insert ) else { do nothing }
public function createUserSocialWallForUser( MongoId $userMongoID, $delimeter ) {
$db = $this->db()->socialWall;
$where = array( 'userId' => $userMongoID,
'delimeter' => $delimeter
);
$data = array( 'userId' => $userMongoID, 'delimeter' => $delimeter, 'event' => array() );
$option = array ('upsert' => true);
$db->update( $where, $data, $option);
}
Sound like a perfect fit for $setOnInsert:
$data = array(
'$setOnInsert' => array(
'userId' => $userMongoID,
'delimeter' => $delimeter,
'event' => array()
)
);
This way the update only sets the values if the upsert needs to do an insert (the not-exists case).
Note that this requires at least v2.4 of MongoDB.

Categories