2014-03-19 4 views
0

현재 PHP 세션 배열을 사용하여 장바구니를 만들고 있습니다. 나는 순수한 멍청 아. 내가 직면 한 문제는 세션 변수가 그에 따라 업데이트되지 않는다는 것입니다. 동일한 제품이 주어질 때 수량을 증가 시키도록되어있다. 그러나 그렇게되지 않습니다 인 print_r ($ 카트)에 대한쇼핑 카트 용 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])); 
} 

?> 

출력된다 NoArray ([28] => 1) { "MSG": "성공", "PNAME": "HTC 하나" "total": 1}

매번 동일한 출력.

+0

여기서 객체 지향 프로그래밍 방법론으로 옮길 것을 강력하게 제안합니다. 즉, 나는'$ cart '가 초기에 설정되는 곳을 보지 못한다. 또한 $ _SESSION [ 'cart'] = array ("id", "qty");'왜 여기에 id와 qty 항목이 있고 왜 배열에 두 개의 값을 넣을 까? 가치에 대해 키와 수량에 제품 ID를 사용하려고 시도하는 것 같습니까?) –

+0

예. 그렇게하고 싶었습니다. 하지만 PHP 배열의 키와 값에 대한 명확한 개념이 없습니다. –

+0

해결책이 무엇이 될지 알려주시겠습니까 ??? –

답변

0

새 세션이 생성 될 때마다 변수 array("id","qty")$_SESSION['cart'] 변수에 저장합니다.

그러나 $pid 세션이 이루어질 때 array("id","qty")을 저장 한으로 사실 수없는 $_SESSION 배열에 있는지 확인하려는 if(in_array($pid, $_SESSION['cart'])) {...} 다음 코드

. 따라서 db update 질의가 없으므로 매번 else 블록으로 갈 때마다 동일한 출력이 생성됩니다.

당신은 $ _SESSION 배열의 $pid을 저장할 필요가 array("id","qty")

코드 :

if (!isset($_SESSION['cart'])){ 
    session_start(); 
    $_SESSION['cart'] = $pid; 
} 

은 또한 당신이 처음에 $ 카트 변수를 초기화해야합니다.

다음

와 in_array()는 그 때 여기에 다수 배열되도록 상기 제 PARAM 필요로 검사

if ($pid == $_SESSION['cart']) {...} or if (in_array($pid, $_SESSION)){...} 

하지

if (in_array($pid, $_SESSION['cart'])){...} 

같아야 경우.

+0

방금 ​​다음과 같이 수정했습니다. if (! isset ($ _ SESSION [ 'cart'])) { session_start(); $ _SESSION [ 'cart'] = $ pid; } // 항목이 배열 인 경우이 경우, 을 추가하지 마십시오 선택하면 (와 in_array ($의 PID, $ _SESSION [ '카트'])) { $ 카트 [$ PID] ++ ; ... ... 여전히 동일한 출력 ... –

+0

어디에도 $ cart 변수를 정의 했습니까? 어떻게 초기화됩니까? $ cart [$ pid] ++의 경우; 작동하려면 먼저 가치가 있어야합니다. –

+0

또한 $ _SESSION [ 'cart']가 $ pid를주는 숫자이기 때문에 in_array는 두 번째 매개 변수를 배열로 사용해야하므로 in_array ($ pid, $ _SESSION [ 'cart'])는 항상 false입니다. if 체크를 if ($ pid == $ _SESSION [ 'cart'])로 변경하십시오. 수정 된 답변을 참조하십시오. –