【发布时间】:2013-12-10 00:41:31
【问题描述】:
将数组变量存储为 cookie 时遇到问题,然后将单独的数组添加到已经包含该数组的 cookie 中
$mysqli = mysqli_connect($db_host,$db_user,$db_pass,$db_base);
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// Displays a message saying product was added to the basket
$message = $_POST['product_name']." was added to the basket";
echo "<script>alert(".$message.")</script>";
// Sets the basket
$itemID = $_POST['product_id'];
$itemQuantity = $_POST['product_quantity'];
if ($itemQuantity > 0)
{
$items = [$itemID, $itemQuantity];
// Returns cookie value as array
$basket_array = (unserialize($_COOKIE['eg_basket']));
// Adds to array into cookie array
$basket = serialize(array_push($basket_array, $items));
// Sets basket back as cookie
setcookie('eg_basket', $basket); // will expire on browser close
// Displays message
echo "<h3 style='text-align:center'>".$_POST['product_name']." was added to the basket</h3>";
echo "<br/>";
echo "<p style='text-align:center'>Please click below to return to the previous page</p>";
}
else
{
echo "<h3 style='text-align:center'>ERROR: ".$_POST['product_name']." was not added to the basket, invalid quantity given</h3>";
}
echo "<form method='POST' action='product_info.php'><input style='display:none' type='number' name='product_id_POST' value='".$_POST['product_id']."'><input style='text-align:center' type='submit' value='Return'></form>";
// close the connection
mysqli_close($mysqli);
?>
我要做的是创建一个 cookie 来存储产品 ID 数组和数量
例如cookie = [[product_id, 数量],[product_id, 数量],.......]; 然而
我很确定情况并非如此,但这是我用来创建篮子 cookie 的代码(如果它不存在)(这可能是 cookie 不接受任何新值的原因
// Checks is cookie is already set - basket only
if (!isSet($_COOKIE['eg_basket']))
{
$basket = serialize([]);
setcookie('eg_basket', $basket); // will expire on browser close
}
谢谢,非常感谢任何帮助
公牛
【问题讨论】:
-
我建议你把cookie改成session,这样更容易管理也更安全^_^