2017-07-06 86 views
2

How cat looks like, there are items added twice我試圖更新購物車會話中的數量,但下面的代碼只增加了第一個項目的數量,然後在兩次添加任何其他項目時執行合併,kidly幫助在php中使用會話將項目添加到購物車

$('.add-to-cart-mt').on('click', function(e){ 
 
     e.preventDefault(); 
 
     var id =$(this).attr('id'); 
 
     $('#add-to-cat-dialog').dialog({ 
 
      autoOpen:false, 
 
      modal:true, 
 
      hide:"pluff", 
 
      show:"slide", 
 
      height:200, 
 
      open: function() { $(".ui-dialog-titlebar-close").hide(); }, 
 
      
 
      buttons:{ 
 
       "Add":function(){ 
 
        $('#add-to-cat-dialog').dialog("close"); 
 
        $.ajax({ 
 
         url: 'add_to_cart.php', 
 
         data: { productId : id }, 
 
         
 
         success: function (data) { 
 
          $('.top-cart-contain').empty(); 
 
          $('.top-cart-contain').load("header_cart_summary.php"); 
 
         }, 
 
         
 
         error :function (data, textStatus, jqXHR) { } 
 
        }); 
 
       }, 
 
       
 
       "Cancel":function(){ 
 
        $(this).dialog("close"); 
 
       } 
 
      } 
 
     }); 
 
     
 
     $('#add-to-cat-dialog').dialog("open"); 
 
    });
session_start(); 
 
require './database.php'; 
 

 
     if(!empty($_GET["productId"])) { 
 
      $id=$_GET["productId"]; 
 
      $productById = $connection->query("SELECT * FROM products WHERE productId='$id';"); 
 
      if($productById && (mysqli_num_rows($productById)>0)){ 
 
       echo 'query ok'; 
 
       $productDetail= mysqli_fetch_assoc($productById); 
 
       $itemArray = array(
 
        $productDetail["productId"]=>array(
 
         'name'=>$productDetail["productName"], 
 
         'id'=>$productDetail["productId"], 
 
         'quantity'=>1, 
 
         'price'=>$productDetail["productPrice"], 
 
         'image'=>$productDetail["productsImage1"] 
 
         ) 
 
        ); 
 
      
 
       if(!empty($_SESSION["cart_item"])) { 
 
        if(in_array($productDetail["productId"],array_keys($_SESSION["cart_item"]))) { 
 
         foreach($_SESSION["cart_item"] as $k => $v) { 
 
          if($productDetail["productId"] == $k) { 
 
            if(empty($_SESSION["cart_item"][$k]["quantity"])) { 
 
             $_SESSION["cart_item"][$k]["quantity"] = 0; 
 
            } 
 
            $_SESSION["cart_item"][$k]["quantity"] += 1; 
 
          } 
 
         } 
 
        } else { 
 
          $_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray); 
 
        } 
 
       } else { 
 
         $_SESSION["cart_item"] = $itemArray; 
 
       } 
 
       
 
       //set product count in the bag 
 
       if(!empty($_SESSION['cart_volume'])){ 
 
        $_SESSION['cart_volume'] += 1; 
 
       } else { 
 
        $_SESSION['cart_volume'] = 1; 
 
       } 
 
       
 
      }else {echo ''. mysqli_error($connection);} 
 
      
 
     } else { 
 
      echo 'no item'; 
 
}
[enter image description here][1]<li class="item col-lg-4 col-md-4 col-sm-6 col-xs-6 "> 
 
           <div class="product-item"> 
 
            <div class="item-inner"> 
 
            <div class="product-thumb has-hover-img"> 
 
             <figure> <a title="Ipsums Dolors Untra" href="single_product.html"> <img class="first-img" src="./productImages/<?php echo $item['productsImage1']; ?>" style="height: 250px;" alt=""> <img class="hover-img" src="../images/products/img05.jpg" alt=""> </a></figure> 
 
             <div class="pr-info-area animated animate2"><a href="quick_view.html" class="quick-view"><i class="fa fa-search"><span>Quick view</span></i></a> <a href="wishlist.html" class="wishlist"><i class="fa fa-heart"><span>Wishlist</span></i></a> <a href="compare.html" class="compare"><i class="fa fa-exchange"><span>Compare</span></i></a> </div> 
 
            </div> 
 
            <div class="item-info"> 
 
             <div class="info-inner"> 
 
             <div class="item-title"> <h4><a title="Ipsums Dolors Untra" href="single_product.html"><?php echo $item['productName']; ?></a></h4> </div> 
 
             <div class="item-content"> 
 
              <div class="rating"> <i class="fa fa-star-o"></i> <i class="fa fa-star-o"></i> <i class="fa fa-star-o"></i> <i class="fa fa-star-o"></i> <i class="fa fa-star-o"></i> </div> 
 
              <div class="item-price"> 
 
              <div class="price-box"> 
 
               <p class="special-price"> <span class="price-label">Special Price</span> <span class="price">Ksh. <?php echo number_format($item['productPrice'], 2) ; ?></span> </p> 
 
               <!--<p class="old-price"> <span class="price-label">Regular Price:</span> <span class="price"> $567.00 </span> </p>--> 
 
              </div> 
 
              </div> 
 
              <div class="pro-action"> 
 
               <button type="button" class="add-to-cart-mt" id="<?php echo $item['productId']; ?>"> <i class="fa fa-shopping-cart"></i><span> Add to Cart</span> </button> 
 
              </div> 
 
             </div> 
 
             </div> 
 
            </div> 
 
            </div> 
 
           </div> 
 
           </li>

+0

你能'的var_dump($ _ GET [ '的productId']);'添加一個項目到購物車後?它說什麼? – proofzy

+0

字符串(1)「5」:其中5表示產品Id的值。 – Ayuka

回答

0

看看PHP手冊:PHP Manual - array_merge()

相關部分:

如果輸入數組具有相同的字符串鍵,則該鍵的後面的值 將覆蓋前一個。 但是,如果數組鍵 包含數字鍵,則後面的值不會覆蓋原始值 值,但會被附加。

帶數字鍵的輸入數組值將重新編號爲 在結果數組中從零開始遞增鍵。

也許您正在使用數字標識。如果是的話,這個ID被轉化成一個數字序列不符合您需要的ID(productIDs)

$itemArray = array(
    $productDetail["productId"]=>array(
     'name'=>$productDetail["productName"], 
     'id'=>$productDetail["productId"], 
     'quantity'=>1, 
     'price'=>$productDetail["productPrice"], 
     'image'=>$productDetail["productsImage1"] 
    ) 
); 

退房本地驗證碼:

$a = array('6' => array('name'=>'john','id'=>'6','quantity'=>1)); 

$b = array('7' => array('name'=>'bill','id'=>'7','quantity'=>1)); 

$c = array('8' => array('name'=>'mike','id'=>'8','quantity'=>1)); 

$d = array('6' => array('name'=>'lucy','id'=>'6','quantity'=>1)); 

$_SESSION["cart_item"] = array_merge($a, $b, $c, $d); 

var_dump($_SESSION["cart_item"]); 
unset($_SESSION["cart_item"]); 

$a = array('six' => array('name'=>'john','id'=>'6','quantity'=>1)); 

$b = array('seven' => array('name'=>'bill','id'=>'7','quantity'=>1)); 

$c = array('eight' => array('name'=>'mike','id'=>'8','quantity'=>1)); 

$d = array('six' => array('name'=>'lucy','id'=>'6','quantity'=>1)); 

$_SESSION["cart_item"] = array_merge($a, $b, $c, $d); 

var_dump($_SESSION["cart_item"]); 

對我來說,結果是:

/am.php:13: 
array(4) { 
    [0] => 
    array(3) { 
    'name' => 
    string(4) "john" 
    'id' => 
    string(1) "6" 
    'quantity' => 
    int(1) 
    } 
    [1] => 
    array(3) { 
    'name' => 
    string(4) "bill" 
    'id' => 
    string(1) "7" 
    'quantity' => 
    int(1) 
    } 
    [2] => 
    array(3) { 
    'name' => 
    string(4) "mike" 
    'id' => 
    string(1) "8" 
    'quantity' => 
    int(1) 
    } 
    [3] => 
    array(3) { 
    'name' => 
    string(4) "lucy" 
    'id' => 
    string(1) "6" 
    'quantity' => 
    int(1) 
    } 
} 
/am.php:26: 
array(3) { 
    'six' => 
    array(3) { 
    'name' => 
    string(4) "lucy" 
    'id' => 
    string(1) "6" 
    'quantity' => 
    int(1) 
    } 
    'seven' => 
    array(3) { 
    'name' => 
    string(4) "bill" 
    'id' => 
    string(1) "7" 
    'quantity' => 
    int(1) 
    } 
    'eight' => 
    array(3) { 
    'name' => 
    string(4) "mike" 
    'id' => 
    string(1) "8" 
    'quantity' => 
    int(1) 
    } 
} 

這顯示了array_merge如何處理數字索引(至少使用PHP 7)。正如你所看到的,即使是鍵入字符串的數字索引也會像數字一樣處理,從而丟失了productIDs引用。

另一件事:你的代碼很容易受到SQL注入:

$id=$_GET["productId"]; 
$productById = $connection->query("SELECT * FROM products WHERE productId='$id';"); 

瞭解更多關於在這裏:​​PHP Manual - SQL Injection

+0

當然,現在,當我的問題聽起來像是檢查$ _GET發送的產品ID是否在$ _session [cart_item]的數組鍵中時的比較。如果比較失敗,我會將新產品合併到會話中。現在的情況是,我點擊添加到產品A上的貓第一次,其合併,這是正確的事情。當我再次點擊添加到購物車上的產品A再次合併這是錯誤的東西,因爲已經應該有一個關鍵具有相同的產品ID,所以它應該只是增加數量。 – Ayuka

+0

我假設productID是一個整數,對不對?假設在第一次調用時,產品不在會話數組中,並且將被array_merge合併......就像PHP手冊所說的那樣,如果您嘗試使用此函數合併數組並將數字作爲索引進行合併,它們將合併索引(直到這裏都是好的)和結果數組(合併後的數組)將會有**新的索引**,使用從零開始的新數值!你可以在第一次和第二次插入同一產品後var_dump會話數組? – Saleiro

+0

string(1)「6」array(1){[6] => array(4){[「name」] => string(7)「Laptops」[「id」] => string(1)「6 「[」quantity「] => int(1)[」price「] => string(4)」3000「}} – Ayuka

0

下面的代碼工作正常,因爲我需要的。感謝-Saleiro的投入。

[The correct output as required[1]

if(!empty($_GET["productId"])) { 
     $id=intval($_GET["productId"]); 
     $productById = $connection->query("SELECT * FROM products WHERE productId='$id' "); 
     if($productById && (mysqli_num_rows($productById)>0)){ 
      $productDetail= mysqli_fetch_assoc($productById); 
      $itemArray = array(intval($productDetail["productId"])=>array('name'=>$productDetail["productName"], 'id'=>intval($productDetail["productId"]), 'quantity'=>1, 'price'=>$productDetail["productPrice"])); 

      $found = false; 
      if(!empty($_SESSION["cart_item"])) { 
        foreach($_SESSION["cart_item"] as $k => $v) { 
         if($productDetail["productId"] == $v['id']) { 
          $found= true; 
          if(empty($_SESSION["cart_item"][$k]["quantity"])) { 
            $_SESSION["cart_item"][$k]["quantity"] = 0; 
          } 
          $_SESSION["cart_item"][$k]["quantity"] += 1; 
          break; 
         } 
        } 
       if(!$found) { 
         $_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray); 
       } 
      } else { 
        $_SESSION["cart_item"] = $itemArray; 
      } 
     }else {echo ''. mysqli_error($connection);} 

     if(!empty($_SESSION['cart_volume'])){ 
       $_SESSION['cart_volume'] += 1; 
      } else { 
       $_SESSION['cart_volume'] = 1; 
      } 

    } else { 
     echo 'no item'; 

}