Dima Knivets
Dima Knivets

Reputation: 2528

Array in session variable (Yii)

I'm trying to accomplish function that adds values to a session variable, which is array, every time user visits certain page. Here's my code from controller:

public function actionPut($id)
    {
        $session=new CHttpSession;
        $session->open();
        if (empty($session['the_variable'])) {
            $session['the_variable'] = array($id);
        }
        else {
            $session['the_variable'][] = $id;
        }
        $session->close();
        $this->render('test', array('session'=>$session));
    }

But it doesn't work. If the variable is empty, it only stores information for the first time. Next time i visit the page it doesn't add value to an array. I've also tried push_array function, but no luck. What is wrong?

Upvotes: 1

Views: 12264

Answers (2)

Onkar Janwa
Onkar Janwa

Reputation: 3950

Try this solution.

public function actionPut($id)
{

     $session = Yii::app()->session;
     if (!isset($session['the_variable']) || count($session['the_variable'])==0) 
     {
         $session['the_variable'] = array($id);
     }
     else {
        $myarr = $session['the_variable'];
        $myarr[] = $id;
        $session['the_variable'] = $myarr;
     }
     $this->render('test', array('session'=>$session));
}

Upvotes: 6

acorncom
acorncom

Reputation: 5955

I think your problem is that you are starting / closing a session yourself. Instead, you should let Yii handle that for you:

    public function actionPut($id)
    {
        $session=Yii::app()->session;
        
        if (empty($session['the_variable'])) {
            $session['the_variable'] = array($id);
        }
        else {
            $session['the_variable'][] = $id;
        }
        
        $this->render('test', array('session'=>$session));
    }

Also, don't close the session yourself, but let Yii handle that as well.

Upvotes: 0

Related Questions