设置cookie并插入数据库

时间:2017-01-19 18:17:09

标签: php mysql session post cookies

我正在修建电子商务网站,我遇到了setcookie()函数问题。

这是我的add_cart文件:

<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/onlineStore/system/init.php';

$product_id = sanitize($_POST['product_id']);

$size = sanitize($_POST['size']);

$available = sanitize($_POST['available']);

$quantity = sanitize($_POST['quantity']);

$item = array();

$item[] = array(

    'id' => $product_id,
    'size' => $size,
    'quantity' => $quantity,
    );

$domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;

$query = $db->query("SELECT * FROM products WHERE id = '{$product_id}'");

$product = mysqli_fetch_assoc($query);

$_SESSION['success_flash'] = $product['title'].' was added to your cart.';


//CHECK TO SEE IF CART COOKIE EXISTS
if($cart_id != ''){

//adding code later

}
else{
    //ADD CART TO THE DATABASE AND SET COOKIE
    $items_json = json_encode($item);

    $cart_expire = date("Y-m-d H:i:s", strtotime("+30 days"));

    $db->query("INSERT INTO cart (itmes,expire_date) VALUES 

('{$items_json}','{$cart_expire}')");

    $cart_id = $db->insert_id;

    setcookie(CART_COOKIE,$cart_id,CART_COOKIE_EXPIRE,'/',$domain,false);

}
?>

另一个文件,我将cookie定义为常量:

<?php 
define('BASEURL',$_SERVER['DOCUMENT_ROOT'].'/onlineStore/');

define('CART_COOKIE','edHjw3345LKJ1z');

define('CART_COOKIE_EXPIRE',time() + (86400 * 30));
?>

当我使用浏览器开发人员工具检查页面时,看起来cookie在页面重新加载后设置但值显示为0,路径显示n / a,域显示n / a,expire显示n / a并且数据未插入数据库。谁知道什么是错的?请帮忙。

我也在我的init.php文件中的if语句中设置了$ cart_id,如下所示:

$cart_id = '';
    //IF COOKIE EXISTS, SET COOKIE TO cart_id
    if(isset($_COOKIE[CART_COOKIE])){

        $cart_id = sanitize($_COOKIE[CART_COOKIE]);
    }

1 个答案:

答案 0 :(得分:0)

所以我通过清除之前设置的旧cookie解决了这个问题,现在一切似乎都在运行。谢谢你的帮助。