Php 将数组添加到存储在cookie中的数组
将数组变量存储为cookie时出现问题,然后将单独的数组添加到已包含该数组的cookie中Php 将数组添加到存储在cookie中的数组,php,html,arrays,cookies,Php,Html,Arrays,Cookies,将数组变量存储为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();
$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);
?>
谢谢,非常感谢您的帮助
Bull如果已发送标题,则无法将cookie发送到浏览器,请参阅 因此,您需要在此处记录您的消息,而不回显任何内容:
echo "<script>alert(".$message.")</script>";
echo“警报(.$message.”);
并确保在您的
setcookie()
行之前没有其他输出发送到浏览器。我建议您从cookie切换到会话,这样更易于管理,也更安全^_^
echo "<script>alert(".$message.")</script>";