[英]php session array for shopping cart is not updating
目前,我正在使用php會話數組制作購物車。 我是一個純粹的菜鳥。 我面臨的問題是會話變量沒有相應地更新。 當使用相同的產品時,應該增加數量。 但是它沒有這樣做:
<?php
session_start();
// get the product id
//$id = isset($_GET['productID']) ;
$pid = $_GET['productID'] ;
/*
* check if the 'cart' session array was created
* if it is NOT, create the 'cart' session array
*/
if(!isset($_SESSION['cart'])){
session_start();
$_SESSION['cart']=array("id","qty");
}
// check if the item is in the array, if it is, do not add
if (in_array($pid, $_SESSION['cart'])){
$cart[$pid]++;
echo "yes";
include "../includes/dbconn.php";
$result=mysql_query("select product_name from mast_product where id=$pid");
$row=mysql_fetch_row($result);
$sizes=sizeof($cart);
print_r($cart);
echo json_encode(array('msg' => 'Success','pname' => $row[0],'total'=> '3'));
}
// else, add the item to the array
else{
$cart[$pid]=1;
echo "No";
include "../includes/dbconn.php";
$result=mysql_query("select product_name from mast_product where id=$pid");
$row=mysql_fetch_row($result);
$sizes=sizeof($cart);
print_r($cart);
echo json_encode(array('msg' => 'Success','pname' => $row[0],'total'=>$cart[$pid]));
}
?>
print_r($ cart)的輸出是:NoArray([28] => 1){“ msg”:“成功”,“ pname”:“ HTC One”,“ total”:1}
每次相同的輸出。
每次創建新會話時array("id","qty")
都將array("id","qty")
在$_SESSION['cart']
變量中。
但是在下面的代碼if(in_array($pid, $_SESSION['cart'])) {...}
您正在檢查$pid
是否在$_SESSION
數組中,因為存儲了array("id","qty")
進行會話時的時間。 因此,每次它轉到您的else塊時,都會生成相同的輸出,因為沒有數據庫更新查詢。
您需要將$pid
存儲在$ _SESSION數組中,而不是array("id","qty")
碼:
if (!isset($_SESSION['cart'])){
session_start();
$_SESSION['cart'] = $pid;
}
另外,您還需要在開始時初始化$ cart變量。
以下是否檢查應該像
if ($pid == $_SESSION['cart']) {...} or if (in_array($pid, $_SESSION)){...}
不
if (in_array($pid, $_SESSION['cart'])){...}
因為in_array()需要第二個參數為數組(此處為數字)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.