Php购物车使用会话更新数量


Php Shopping Cart Update quantity using Sessions

发布

这个问题后我想出的另一个解决方案,而不是每次我都可以说时使用 for 循环添加一个:

$session->cart[$params->id] => $qty;

我发现这是一种更好的方法,因为您可以通过这种方式更新购物车,而不是将所需的数字添加到购物车中已有的数量上。

对于所有阅读这篇文章的人,我想出了一个使用处理程序更新购物车的解决方案。 具体如下。首先在详细信息的形式部分.php

<form method="post"> //should be added to retrieve the qty data from the text field.

接下来在处理程序中 . . .添加以下循环和变量

$qty = $_POST['qty']; or $qty = $_REQUEST['qty'];

然后

for($i =0; $i < $qty ; $i++){
  ++$session->cart[$params->id];
}

我正在使用php创建一个购物车网站来处理一些任务。我在更改购物车中商品的数量时遇到困难。这是我的代码,我用它来获取输入处理提交并在购物车视图中显示数量

详情.php:

    <form id="cart_form" action="handler-add-cart.php">
     <input type="hidden" name="id" value="<?php echo $product->id ?>" />
     <input type="submit" value="add to cart"/>
    **Quantity:<input type="text" name="qty" />**
    </form>

handler_add_cart.php:

<?php
require_once "include/Session.php";
$session = new Session();
**$params = (object) $_REQUEST;
++$session->cart[$params->id];**
header("location: cart.php");

购物车.php:

 <?php
    require_once "include/Session.php";
    $session = new Session();
    require_once "include/db.php";
    // The $cart array simplifies the view generation below, keeping 
    // computations and database accesses in this controller section.
    $cart = array();
    if (isset($session->cart)) {
    $total = 0;
    foreach ($session->cart as $prod_id => $qty) {
    $product = R::load("products", $prod_id);
    $total += $qty * $product->price;
    $entry = new stdClass();  // entry will contain info for table
    $entry->id = $prod_id;
    $entry->price = $product->price;
    $entry->name = $product->name;
    **$entry->qty =  $qty ;**
    $cart[] = $entry;
    }
    }
    ?>

在这里我删除了一些 html 以专注于我的问题,我在文件中有所有标签,所以这不是问题

    <h2>Cart</h2>
    <?php if (count($cart)): ?>
     <table id="display">
      <tr>
       <th>product</th><th>id</th><th>quantity</th><th class='price'>price</th>
      </tr>
      <?php foreach ($cart as $entry): ?>
       <tr>
        <td><a href="details.php?id=<?php echo $entry->id ?>"
            ><?php echo $entry->name ?></a></td>
        <td><?php echo $entry->id ?></td>
        **<td class='qty'><?php echo $entry->qty ?></td>**
             i cleared these fields below to not distract from the issue im having
        <td >
         </td>
       </tr>
      <?php endforeach ?>
      <tr>
       <th >
       </th>
      </tr>
     </table>

    </body>
    </html>

要使用在表单中输入的值增加数量,请:-

$entry->qty =  $qty + $_POST['qty'];

尽管您可能希望验证用户是否已输入数字并且表单是否已发布,但您可能希望以下内容:

if (isset($_POST['qty']) && is_numeric($_POST['qty])) {
   $entry->qty =  $qty + $_POST['qty'];
}
else
{
   $entry->qty =  $qty;
}