Php array in session var

Store array of objects in PHP session

To get an item from the cart, you will need this function: Solution 4: Try not pushing to array, because its probably not set yet, but to store to session, create new session var by: to remove it: EDIT: Thanks to comments I realized that above code wouldn’t store array in session. My understanding is that when you serialize an object and pass it through a session, for example, from index.php page to securePage.php, SESSION just passes that objects data, therefore, you can not use that object’s functions.

Store array of objects in PHP session

How can I store/remove/get an array of objects in the PHP session?

array_push($_SESSION['cart'], serialize($item)); 

It’s Work For Me.
if this code Report Errors Please Comment to Check this.
Please check PHP version

You also need another 2 > to close your if() and for() statements so it’s like this:

Have you tried using this?

if(!isset($_SESSION['cart'])) < $_SESSION['cart'] = []; >$_SESSION['cart'][] = $item; 

You don’t need to serialize the item-variable — a Session can store pure Objects, as long as the max. session-size doesn’t exceed.

If you want to remove Items from the cart, you should use index-Names — this allows you to find your items faster.

Читайте также:  Python str to bits

I would probably use something like this:

if(!isset($_SESSION['cart'])) < $_SESSION['cart'] = []; >function addItem($itemName)< if(!isset($_SESSION['cart'][$itemName])) < $_SESSION['cart'][$itemName] = 1; >else $_SESSION['cart'][$itemName] ++; > > function removeItem($itemName) < if(isset($_SESSION['cart'][$itemName])) < if($_SESSION['cart'][$itemName] >0) < $_SESSION['cart'][$itemName] --; >> > function clearCart()

In this case, the cart stores each item and its amount. Instead of $itemName , you could also use the item-ID from your database.

To get an item from the cart, you will need this function:

function getItemCount($itemName) < if(isset($_SESSION['cart'][$itemName])) < return $_SESSION['cart'][$itemName]; >return 0; > 

Try not pushing to array, because its probably not set yet, but to store to session, create new session var by:

$_SESSION['cart']=serialize($item); 

Thanks to comments I realized that above code wouldn’t store array in session. So, another short solution is to store to session var some JSON. Try this for a short test:

$tmp = array(1,2,3); $_SESSION['cart']=json_encode($tmp); print_r(json_decode($_SESSION['cart'])); 

If that array is associative, you shoud use for decode:

json_decode($_SESSION['cart'], true); 

How to get PHP session variable deeply nested inside array?, Two ways: 1 Convert to stdClass: $stdClass = json_decode(json_encode($_SESSION)); Then access with [] . 2 Convert to array: $array

Create a PHP Session Class and Objects

In this recording I revise PHP session handling and storage then show you how you can create Duration: 1:25:11

PHP — $SESSION Variables

Is there a way to pass an object through sessions and use its functions?

My understanding is that when you serialize an object and pass it through a session, for example, from index.php page to securePage.php, SESSION just passes that objects data, therefore, you can not use that object’s functions. The only way is to create a new object on securePage.php with the data you have passed. Is there a way to pass an actual object and then use it’s functions without creating a brand new object on securePage.php.

$randomObj = new rndObject; $_SESSION['object'] = serialize($randomObj); 
$whatever = unserialize($_SESSION['object']); //below code won't work and say something like //Fatal error: Call to a member function checkAccess() on a non-object in //securePage.php on line 39 echo $whatever->checkAccess(); 

Sort of, to get the object which has been loaded into SESSION, you need to include the class definition somewhere before calling unserialize and it will work as you expect, but it will still, technically, create a new instance.

You should use __sleep() and __wakeup() magic methods (that’s what it’s for) :

Php saving object in session, As far as the php compiler is concerned all you are doing is writing an object (serialised) to an Array its a different process that ensures $_SESSION is

Using session variable with objects

I have created an object and assigned values as follows:

$car_object->offer = 'Sale'; $car_object->type = 'Sport Car'; $car_object->location = "Buffalo, New york"; 

How can I store the $car_object inside a session variable? How can I get the $car_object out from the session variable?

$car_object = new Car(); $car_object->offer = 'Sale'; $car_object->type = 'Sport Car'; $car_object->location = "Buffalo, New york"; $_SESSION['car'] = $car_object; 
$car_object = $_SESSION['car']; echo $car_object->offer; 

A more simpler way would be to do:

class SessionObject < public function __construct($key) < if(isset($_SESSION[$key])) < $_SESSION[$key] = array(); >$this->____data &= $_SESSION[$key]; > public function __get($key) < return isset($this->___data[$key]) ? $this->___data[$key] : null; > public function __set($key,$value) < $this->___data[$key] = $value; > > 

Then you can use something like this;

class CarSession extends SessionObject < public function __construct() < parent::__construct('car'); //name this object >/* * Custom methods for the car object */ > $Car = new CarSession(); if(!$car->type) < $Car->type = 'transit'; > 

this helps for a more manageable framework for storing objects in the session.

class Currentuser extend SessionObject<> class LastUpload extend SessionObject<> class UserData extend SessionObject<> class PagesViewed extend SessionObject<> 

Serializing the object and storing it into session works. Here is an entire discussion about this: PHP: Storing ‘objects’ inside the $_session

Create a PHP Session Class and Objects, In this recording I revise PHP session handling and storage then show you how you can create Duration: 1:25:11

How to save many objects in a $session array variable

I’m new in the object oriented programming so this question might be silly.

I’ve created my class in a separate file called classProduct.php

prodId = $prodId; $this->prodName=$prodName; $this->prodPrice=$prodPrice; > public function get_prodId()< return $this->prodId; > public function get_prodName()< return $this->prodName; > public function get_prodPrice()< return $this->prodPrice; > > ?> 

Then I tried to create a new object in a $_SESSION variable. This happens in another file called dailySales.php where I include the previous file using:

include_once("classProduct.php"); 

What I want to do is to save in $_SESSION[‘myItems’] each new object. I am trying something like:

$newItem= new product($var,$var,$var); $_SESSION['myItems']=array($newItem); // I believe here is where I do it wrong 

Every time the buyer chooses one more products, the pages reloads (with ajax). When I echo or var_dump the $_SESSION[‘myItems’] I only get the last object. What do I need to change to get it working correctly?

Of course I do need the object so I can easily remove a product from the shopping cart if ‘Delete’ is pressed.

This is working for me locally.

Define your items session variable as an array, then push them into the variable using array_push

class product < public $prodId; public $prodName; public $prodPrice; public function __construct($prodId, $prodName, $prodPrice) < $this->prodId = $prodId; $this->prodName = $prodName; $this->prodPrice = $prodPrice; > public function get_prodId() < return $this->prodId; > public function get_prodName() < return $this->prodName; > public function get_prodPrice() < return $this->prodPrice; > > 
$product = new product(1, "test", 23); $product2 = new product(2, "test2", 43); $_SESSION['items'] = array(); array_push($_SESSION['items'], $product, $product2); echo '
'; print_r($_SESSION['items']); echo '

';

This is the output of print_r()

Array ( [0] => product Object ( [prodId] => 1 [prodName] => test [prodPrice] => 23 ) [1] => product Object ( [prodId] => 2 [prodName] => test2 [prodPrice] => 43 ) ) 

How can I store objects in a session in PHP?, PHP’s native $_SESSION sessions transparently serialize and unserialize objects that support PHP’s serialization protocol or the Serializable interface.

Источник

PHP: Storing an array in a session variable.

This is a tutorial on how to store a PHP array in a session variable. Typically, this sort of design is used on eCommerce websites, where the user is able to add multiple products to their cart. Because the cart is a temporary list, many developers will opt to store it in the user’s session.

Storing an array in a session variable is simple, and it works exactly the same as storing string values or whatnot. Have a look at the following PHP code snippet:

If you run the code above, you’ll see that our session variable contains the $cartArray. The output of our var_dump will look like this:

array (size=3) 0 => int 123 1 => int 12 2 => int 490

Looping over the session array.

But what if we want to loop through this cart array?

  • We make sure that the session variable in question actually exists. This is important, as we can never be sure that a particular session variable has been set. If we attempt to iterate over a session array that does not exist, our application will throw out a number of PHP warnings, such as “Warning: Invalid argument supplied for foreach() “
  • We loop through the session array like we would with a regular PHP array. We print out the product ID of the cart item for testing purposes.

To make sure that our session array always exists, we could use the following code:

Here, we check to see if “cart” has been set. If not, we create an empty session array.

Adding elements to the array.

So, what if we want to add items to our session array?

As you can see – our session array works the exact same way as a regular PHP array. If you run and refresh the script above, you’ll see that a new element is added on every page load. This is what my session looked like after multiple refreshes:

array (size=1) 'cart' => array (size=6) 0 => int 123 1 => int 12 2 => int 490 3 => int 2787376 4 => int 2787376 5 => int 2787376

Hopefully, you found this tutorial to be helpful!

Источник

Массив в сессию

Как сохранять массив в сессию PHP?
Подскажите пожалуйста как при каждом заходе на страницу сохранять две переменные в массив сессии и.

Как записать в сессию массив с индексами?
есть массив $a=array(); $a=’1 3 4 8 2 5′; //где 1 3 4 8 2 5 значения массива.Мне нужно в сессию.

Как добавить массив в сессию с помощью PHP
Скажите пожалуста, как добавить массив в сессию с помощью PHP (ООП)?

Прописали в начале обоих файлов ?

Ключ $frukt в $_SESSION[‘$frukt’] все таки переменная или строка ?
и вывод должен быть

ЦитатаСообщение от Kanred Посмотреть сообщение

Я незнаю что это, но ваш код заработал.

Я счас собрал этот код и он пока работает:

$alfav = array(1=>'А','Б','В','Г','Д'); $_SESSION['alfav'] = isset($_SESSION['alfav']) ? $_SESSION['alfav']=$alfav : "Пусто"; echo $_SESSION['alfav'][3];
$_SESSION['alfav'] = isset($_SESSION['alfav']) ? $alfav : "Пусто";
unset($_SESSION[alfav]); unset($_SESSION['$frukt'][2];

Kanred,
И как же быть, я вроде букву то удалил, но она опять подгружается в сессию вышестоящим этим кодом?

Какие тут можно придумать варианты чтобы уйти от этого?

Добавлено через 5 минут
Если я был прав и так оно и есть что удаленная буква подгружается, то как уйти от этого можно? загрузив например алфавит в сессию только один раз при помощи кнопки на странице каким либо способом?
(заполнить через цикл, заполнить его из базы, (заполнить )взять его из другой страницы?) Или что делать то?

$_SESSION['alfav'] = array(1=>'А','Б','В','Г','Д'); unset($_SESSION['alfav'][1]); //После удаления проверьте массив print_r($_SESSION['alfav']);
for ($i = 192; $i  (192+32); $i++) echo iconv('Windows-1251', 'UTF-8', chr($i));

Давайте как нибудь и его применим, а может и массив им заполним как нибудь?

for ($i = 192; $i  (192+32); $i++) $alfav[$i - 191]= iconv('Windows-1251', 'UTF-8', chr($i)); echo $alfav[7];

Такой способ подойдет или есть еще какие?

Kanred,
Да вроде работает ваш способ, видимо переменную то что убрали из кода.

Я еще что хотел спросить- когда все буквы удалятсяих нужно будет снова восстановить!
Как это можно проделать? Обратится к другому php- файлу через форму которая кинет на php- обработчик? который в свою очередь заполнит сессию алфавитом и вернет назад на страницу, так?

Источник

Оцените статью