Let me see
Let me see

Reputation: 5094

Storing array in sessions

I am trying to store some data as an array in the session but the function does not seem to be working.it does not throw any error but every time i add data to it, it just overwrites the previous data. I am using yii and here is the action

public function actionStoreProducts($name)
        {
            $name=trim(strip_tags($name));
            if(!empty($name))
            {
                if(!isset(Yii::app()->session['_products']))
                {
                    Yii::app()->session['_products']=array($name);  
                    echo 'added';
            }
            else
            {

                $myProducts = Yii::app()->session['_products'];
                $myProducts[] = $name;
                Yii::app()->session['products'] = $myProducts;
                echo 'added';

            }

        }

Can anyone suggest me how can i achieve the desired result?

Upvotes: 1

Views: 1632

Answers (3)

Alireza Fallah
Alireza Fallah

Reputation: 4607

session property read-only i think the correct aproach is :

function actionStoreProducts($name) {
    $session = new CHttpSession;               //add this line
    $session->open();                          //add this line
    $name = trim(strip_tags($name));
    if (!empty($name)) {
        if (!isset(Yii::app()->session['_products'])) {
            $session->add('_products', array($name));   //replace this line
            echo 'added';
        } else {

            $myProducts = Yii::app()->session['_products'];
            $myProducts[] = $name;
            $session->add('_products', $myProducts);    //replace this line
            echo 'added';
        }
    }
}

Upvotes: 2

Dharmendra
Dharmendra

Reputation: 127

first get an variable into $session['somevalue'] ,then sore in array variable, Use Like IT:-

    $session = new CHttpSession;
    $session->open();

    $myval = $session['somevalue'];
    $myval[] = $_POST['level'];
    $session['somevalue'] = $myval;

Upvotes: 1

Chaulagai
Chaulagai

Reputation: 752

Please correct your code like this .

public function actionStoreProducts($name) {
        $name = trim(strip_tags($name));
        if (!empty($name)) {
            if (!isset(Yii::app()->session['_products'])) {
                Yii::app()->session['_products'] = array($name);
                echo 'added';
            } else {

                $myProducts = Yii::app()->session['_products'];
                $myProducts[] = $name;
                Yii::app()->session['_products'] = $myProducts;
                echo print_r(Yii::app()->session['_products']);
                echo 'added';
            }
        }
    }

Upvotes: 3

Related Questions