在数据库中存储Cart的值

i am developing a e-commerce project in Codeigniter. I want that any user can add products in cart but when he want to checkout he has to logged in the website after that he can checkout. But when i tried this after user login the cart data is lost. How can i store the data before the checkout so that data in the cart not lost. for solving this i have tried another way that I have stored the cart data in the data base . For storing cart data to database i have used the code below :- Controller code

class Shopping_Cart extends CI_Controller {
public $cart_id = "";
 function add_to_cart()
      {$data = array(
                        'id'    => $this->input->post('product_id'), 
                        'name'  => $this->input->post('product_name'), 
                        'price' => $this->input->post('product_price'), 
                        'qty'   => 1, 
                        "image" =>$this->input->post('product_image'), 
                      );
            $this->cart->insert($data);
       if($this->cart_id)
        {
            $this->updatecarttodb($this->cart->contents());                     
        }
        else
        {           
            $this->addcarttodb($this->cart->contents());
        }       

         echo $this->view_cart(); 
       }
private function addcarttodb($cartdata)
    {
        $cart_id = $this->Cart_model->addtoCart($cartdata);
        $cookie = array(
                            'name'   => 'cart_id',
                            'value'  => $cart_id,
                            'expire' => (365*60*60*24),
                            'domain' => '',
                            'path'   => '/',
                            'prefix' => '',
                            'secure' => FALSE
                        );
        $this->input->set_cookie($cookie);
    }
    private function updatecarttodb($cartdata)
    {
        $this->Cart_model->updateCart($this->cart_id,$cartdata);        
    }

Model Code

function addtoCart($cartData)
{
  $cartData = array("cart_data"=>serialize($cartData));
  $this->db->insert('tbltmpcart',$cartData);     
  return $this->db->insert_id();
}

function updateCart($cart_id,$cartData)
{
  if($cart_id == "")return;
  if($cartData != "")
   {
     $cartData = serialize($cartData);
   }
    $updateData = array("cart_data"=>$cartData);
    $this->db->where("cart_id",$cart_id);   
    $this->db->update('tbltmpcart',$updateData);           
}

function getCartContents($cart_id)
{
  $this->db->where("cart_id",$cart_id);
  $result = $this->db->get('tbltmpcart');
  if($result && $result->num_rows())
  {
    $retdata = $result->result_array();                
    if($retdata[0]['cart_data'] != "1" && $retdata[0]['cart_data'] != "")
    {
      return @unserialize($retdata[0]["cart_data"]);
    }     
  }
  return "";
}

my problem is that $cart_id value not retain it is lost so i can not use further. If there is any problem in the code the try to correct my code.