简体   繁体   English

使用 PHP $_Session 的购物车

[英]Shopping cart using PHP $_Session

I'm learning PHP and I'm trying to create a shopping cart using only PHP and $_SESSION我正在学习 PHP 并且我正在尝试仅使用 PHP 和 $_SESSION 创建购物车

What I'm trying to achieve is:我想要实现的是:

  • Adding an existing product only updates a quantity variable添加现有产品只会更新数量变量
  • A delete button that decreases a quantity variable and then removes the item from the cart when quantity = 0一个删除按钮,用于减少数量变量,然后在数量 = 0 时将商品从购物车中删除
  • A clear cart button which removes everything from the cart一个清除购物车按钮,可从购物车中删除所有内容

My current problems are:我目前的问题是:

  • Products can be added multiple times but the item keeps reappearing in the cart and the quantity isn't updated.产品可以多次添加,但该项目会不断重新出现在购物车中,并且数量不会更新。
  • Neither the delete button nor clear cart button is currently working.删除按钮和清除购物车按钮当前都不起作用。

I'm struggling with implementing a global quantity variable, I don't understand how to manage it and update it.我正在努力实现一个全局数量变量,我不明白如何管理和更新它。

I feel like I'm being a bit hopeful/naive with my delete function and that the array check is off, but I'm unsure how to fix it.我觉得我对删除 function 并且阵列检查已关闭有点希望/天真,但我不确定如何修复它。

I think that the reset cart function is close, but I'm short one step.我认为重置车 function 很接近,但我还差一步。 I just don't know where我只是不知道在哪里

Any help would be or a nudge in the right direction would be appreciated, thanks in advance.任何帮助或朝正确方向轻推将不胜感激,在此先感谢。

My code我的代码

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

Welcome to Stack Overflow!欢迎来到堆栈溢出!

There is one major issue with your code:您的代码存在一个主要问题:

foreach loop and assignment: foreach循环和赋值:

foreach ( $items as $ino => $item ) { in combination with echo "<button type='submit' name='buy' value='$ino'>Buy</button> "; foreach ( $items as $ino => $item ) {结合echo "<button type='submit' name='buy' value='$ino'>Buy</button> "; is dangerous.很危险。 $ino refers to the array index, in the moment a new product is added somewhere in the list (and not at the end of it) all elements in the cart might point to the wrong product. $ino指的是数组索引,当一个新产品被添加到列表中的某处(而不是在它的末尾)时,购物车中的所有元素都可能指向错误的产品。

Example:例子:

You have an array with ['Apple', 'Orange', 'Banana'] .你有一个带有['Apple', 'Orange', 'Banana']的数组。 User decides to add all three to the cart.用户决定将这三个都添加到购物车中。 The cart now contains [0, 1, 2] or "Apple, Orange, Banana" .购物车现在包含[0, 1, 2]"Apple, Orange, Banana"

If these values would now come from a database, someone might have added "Strawberry" to the list and reordered the catalog so the new array would be something like ['Apple', 'Strawberry', 'Orange', 'Banana'] .如果这些值现在来自数据库,则可能有人将“Strawberry”添加到列表中并重新排序目录,因此新数组将类似于['Apple', 'Strawberry', 'Orange', 'Banana'] The cart would still have the old values [0, 1, 2] and would now point to "Apple, Strawberry, Orange" .购物车仍将具有旧值[0, 1, 2]并且现在将指向"Apple, Strawberry, Orange" Instead use a product ID right from the start.而是从一开始就使用产品 ID。

Fix and a bit of help:修复并提供一些帮助:

I am not going to write your code as you want to learn it yourself.我不会写你的代码,因为你想自己学习。 But just to give you some advice and help here are some hints.但只是为了给你一些建议和帮助,这里有一些提示。

Use a product 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 ],
]; 

Use the key in the cart session variable:使用cart session 变量中的密钥:

In the loop use the ID as product reference:在循环中使用 ID 作为产品参考:

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

... and increment the value by one if it is already in the cart... ...如果它已经在购物车中,则将值加一...

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

Then decrement the value using the same approach for the delete button.然后使用与删除按钮相同的方法减小值。

Resetting the cart:重置购物车:

The cart won't get cleared as you are checking for $_POST["reset"] but the button has the name "clear": <button type='submit' name='clear'>Clear cart</button> .当您检查$_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