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);
}
型号代码
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 "";
}
我的问题是$ cart_id值无法保留,因此丢失了,所以我无法再使用了。如果代码中有任何问题,请尝试更正我的代码。