簡體   English   中英

使用 PHP $_Session 的購物車

[英]Shopping cart using PHP $_Session

我正在學習 PHP 並且我正在嘗試僅使用 PHP 和 $_SESSION 創建購物車

我想要實現的是:

  • 添加現有產品只會更新數量變量
  • 一個刪除按鈕,用於減少數量變量,然后在數量 = 0 時將商品從購物車中刪除
  • 一個清除購物車按鈕,可從購物車中刪除所有內容

我目前的問題是:

  • 產品可以多次添加,但該項目會不斷重新出現在購物車中,並且數量不會更新。
  • 刪除按鈕和清除購物車按鈕當前都不起作用。

我正在努力實現一個全局數量變量,我不明白如何管理和更新它。

我覺得我對刪除 function 並且陣列檢查已關閉有點希望/天真,但我不確定如何修復它。

我認為重置車 function 很接近,但我還差一步。 我只是不知道在哪里

任何幫助或朝正確方向輕推將不勝感激,在此先感謝。

我的代碼

<?php
session_start ();

$items = [
[ "name" => "Lord of the Rings", "price" => 16.72 ],
[ "name" => "The Name of The Wind", "price" => 35.54 ],
[ "name" => "The Way of Kings", "price" => 32.237 ],
[ "name" => "Gravity Rising", "price" => 24.75 ],
[ "name" => "The Hobbit", "price" => 30.30 ],
]; 

//loads cart
if (! isset ( $_SESSION ['cart'] )) {
    $_SESSION ['cart'] = array ();
    
       //Attempt to add quantity variabke for cart
       // for ($i = 0; $i < count($products); $i++) {
       // $_SESSION["qty"][$i] = 0;
       //}
}

// Add
if (isset ( $_POST ["buy"] )) {
     
    //Atempt to add quantity variable 
    //If item is already in cart, quantity += 1. Else add item.
    //if (in_array($_POST ["buy"], $_SESSION['cart'])) {
       $_SESSION ['cart'][] = $_POST["buy"];
       
        
    //}
}

// Delete Item
else if (isset ( $_POST ['delete'] )) { 
    if (false !== $key = array_search($_POST['delete'], $_SESSION['cart'])) { // check item in array
    unset($_SESSION['cart'][$key]); // remove item
    }


    
}

// Empty Cart
else if (isset ( $_POST ["reset"] )) { // remove item from cart
    unset ( $_SESSION ['cart'] );
}

?>

<form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='post'>
  <form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='post'>
    <?php
        foreach ( $items as $ino => $item ) {
            $name = $item ['name'];

            $price = $item ['price'];

            echo " <p>$name</p>";
            echo '<p>$' . number_format((float)$item['price'], 2, '.', '') . '</p>';

            
            echo "<button type='submit' name='buy' value='$ino'>Buy</button> ";
        }

            
        
    ?>
</form>


<?php
if (isset ( $_SESSION ["cart"] )) {
    ?>

<form action='(omitted link)'
target='_blank' method='post'
enctype='application/x-www-form-urlencoded'>
<table>
    <tr>
        <th>Product</th>
        <th>Price</th>
        <th>Quantity</th>
        <th>Action</th>
    </tr>
   <?php
// Set a default total
$total = 0;
foreach ( $_SESSION['cart'] as $ino ) {
    ?>
<tr>
    <td>
        <?php echo $items[$ino]['name']; ?>
    </td>
    <td>
        <?php echo  number_format((float)$items[$ino]['price'], 2, '.', ''); ?>
    </td>
    <td>
        Quantity: <?php echo "";?>        
    </td>
    <td>
        <button type='submit' name='reset' value='<?php echo $ino;    ?>'>Delete</button>
    </td>
</tr>
<?php
    $total += number_format((float)$items[$ino]['price'], 2, '.', '');
} // end foreach
?>

Total: $<?php echo $total; ?>
    <tr>
        <td colspan="2">Total: $<?php echo($total); ?></td>
        
    </tr>
    <tr>
        <td><button type='submit' name='clear'>Clear cart</button></td>
    </tr>
</table>
</form>
<?php  } ?>

歡迎來到堆棧溢出!

您的代碼存在一個主要問題:

foreach循環和賦值:

foreach ( $items as $ino => $item ) {結合echo "<button type='submit' name='buy' value='$ino'>Buy</button> "; 很危險。 $ino指的是數組索引,當一個新產品被添加到列表中的某處(而不是在它的末尾)時,購物車中的所有元素都可能指向錯誤的產品。

例子:

你有一個帶有['Apple', 'Orange', 'Banana']的數組。 用戶決定將這三個都添加到購物車中。 購物車現在包含[0, 1, 2]"Apple, Orange, Banana"

如果這些值現在來自數據庫,則可能有人將“Strawberry”添加到列表中並重新排序目錄,因此新數組將類似於['Apple', 'Strawberry', 'Orange', 'Banana'] 購物車仍將具有舊值[0, 1, 2]並且現在將指向"Apple, Strawberry, Orange" 而是從一開始就使用產品 ID。

修復並提供一些幫助:

我不會寫你的代碼,因為你想自己學習。 但只是為了給你一些建議和幫助,這里有一些提示。

使用產品 ID:

$items = [
[ "pid" => "LOTR", "name" => "Lord of the Rings", "price" => 16.72 ],
[ "pid" => "NameWind", "name" => "The Name of The Wind", "price" => 35.54 ],
[ "pid" => "WayKings", "name" => "The Way of Kings", "price" => 32.237 ],
[ "pid" => "GravRi", "name" => "Gravity Rising", "price" => 24.75 ],
[ "pid" => "Hobbit", "name" => "The Hobbit", "price" => 30.30 ],
]; 

使用cart session 變量中的密鑰:

在循環中使用 ID 作為產品參考:

$pid = $item ['pid'];
echo "<button type='submit' name='buy' value='$pid'>Buy</button> ";

...如果它已經在購物車中,則將值加一...

if (isset ( $_POST["buy"] )) {
    if (array_key_exists($_POST["buy"], $_SESSION['cart'])) {
      $_SESSION['cart'][$_POST["buy"]] += 1;
    } else {
      $_SESSION['cart'][$_POST["buy"]] = 1;
    }
}

然后使用與刪除按鈕相同的方法減小值。

重置購物車:

當您檢查$_POST["reset"]時,購物車不會被清除,但按鈕的名稱為“clear”: <button type='submit' name='clear'>Clear cart</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM