将数组变量存储为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的数组; s和数量
e.g。 cookie = [[product_id,quantity],[product_id,quantity],.......]; 然而
我很确定情况并非如此,但这是我用来创建购物篮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
}
谢谢,非常感谢任何帮助
牛
答案 0 :(得分:1)
如果已经发送了标题,则无法向浏览器发送Cookie,请参阅the manual。
因此,您需要在不回复任何内容的情况下记录您的消息:
echo "<script>alert(".$message.")</script>";
并确保在setcookie()
行之前没有其他输出发送到浏览器。