2012-05-23 66 views
0

我有一個籃子餅乾,在將產品添加到籃子之前,該功能會檢查cookie是否存在或是否需要新cookie。這在一次添加一個項目時正常工作,但有時會同時添加多個項目。再次,如果舊的籃子cookie存在這工作正常。問題是當沒有籃子cookie存在和功能必須創建一個。cookie沒有被直接設置

它第一次經歷,cookie被創建一個數據庫記錄被添加等。

繞第二圈時,我們檢查是否有cookie被發現的cookie中的功能與其它cookie的創建等

$this->db->select('basket_id'); 
    $this->db->from($this->basket_table); 
    $this->db->where('basket_id', get_cookie('basket_id')); 
    $check_basket = $this->db->get(); 

if($check_basket->num_rows > 0){ 
    $basket_exists = 1; 
}else{ 
    $basket_exists = 0; 
} 

if($basket_exists == 0){ 
    delete_cookie('basket_id'); 

    $basket = array(
    'lang_id' => $lang_id, 
    'currency_id' => $currency_id, 
    'customer_id' => $customer_id, 
); 

    $this->db->insert($this->basket_table, $basket); 
    $basket_id = $this->db->insert_id();; 

    $cookie = array(
    'name' => 'basket_id', 
    'value' => $basket_id, 
    'expire' => 60*60*24*30, 
    'domain' => 'REMOVED' 
    'path' => '/', 
    'prefix' => '', 
); 

    set_cookie($cookie); 
}else{ 
    $basket_id = get_cookie('basket_id'); 
} 

回答

1

爲了設置cookie,你需要把它發送到瀏覽器, - 但是如果您的函數在創建視圖之前多次循環,這種情況就不會發生。

所以事先設置cookie將它們用籃子,或者只檢查如果cookie需要設置一次,這樣的:

$this->db->select('basket_id'); 
    $this->db->from($this->basket_table); 
    $this->db->where('basket_id', get_cookie('basket_id')); 
    $check_basket = $this->db->get(); 

if($check_basket->num_rows > 0) { 

    $basket = array(
    'lang_id' => $lang_id, 
    'currency_id' => $currency_id, 
    'customer_id' => $customer_id, 
); 

    $this->db->insert($this->basket_table, $basket); 
    $basket_id = $this->db->insert_id(); 

    $cookie = array(
    'name' => 'basket_id', 
    'value' => $basket_id, 
    'expire' => 60*60*24*30, 
    'domain' => 'REMOVED' 
    'path' => '/', 
    'prefix' => '', 
); 

    set_cookie($cookie); 
} 

// Now run your basket logic here - knowing the cookie is setup 

}