【问题标题】:Shopping cart using PHP $_Session使用 PHP $_Session 的购物车
【发布时间】:2020-11-04 10:38:44
【问题描述】:

我正在学习 PHP,我正在尝试仅使用 PHP 和 $_SESSION 创建一个购物车

我想要实现的是:

  • 添加现有产品只会更新数量变量
  • 一个删除按钮,用于减少数量变量,然后在数量 = 0 时从购物车中删除商品
  • 一个清除购物车按钮,可从购物车中删除所有物品

我目前的问题是:

  • 产品可以多次添加,但商品会不断重新出现在购物车中,并且数量不会更新。
  • 删除按钮和清除购物车按钮当前都不起作用。

我正在努力实现一个全局数量变量,我不明白如何管理和更新它。

我觉得我的删除功能有点希望/天真,并且数组检查已关闭,但我不确定如何修复它。

我认为重置购物车功能很接近,但我还差一步。我只是不知道在哪里

任何帮助或朝正确方向轻推将不胜感激,在此先感谢。

我的代码

<?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  } ?>

【问题讨论】:

    标签: php html session-variables shopping-cart


    【解决方案1】:

    欢迎来到 Stack Overflow!

    您的代码存在一个主要问题:

    foreach 循环和赋值:

    foreach ( $items as $ino =&gt; $item ) {echo "&lt;button type='submit' name='buy' value='$ino'&gt;Buy&lt;/button&gt; "; 结合使用是危险的。 $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会话变量中的键:

    在循环中使用 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”:&lt;button type='submit' name='clear'&gt;Clear cart&lt;/button&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-17
      • 2021-12-18
      • 2015-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-30
      相关资源
      最近更新 更多