繁体   English   中英

购物车的php会话数组未更新

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM