【问题标题】:Adding Multiple Products to Basket using PHP Sessions使用 PHP 会话将多个产品添加到购物篮
【发布时间】:2021-04-09 14:58:00
【问题描述】:

我为电子商务网站构建了一个购物篮/结账系统,并使用会话变量来存储产品名称、价格和数量,并且可以将它们显示在我的结账页面上。 我正在努力将不同的产品添加到购物篮中,当用户转到另一个产品并单击添加到购物篮按钮时,它会从购物篮中删除第一个产品。有谁知道我可以如何更改我的代码,以便可以将不同的产品添加到购物篮中,而无需删除当前在变量中的任何产品。以及如何将数量添加到 URL 中,以便将其添加到购物篮中。数量是产品页面上的一个输入框,用户可以尝试输入产品的数量。

这是我的产品页面 -

<?php
require('includes/application_top.php');
$page_title='Details';
require('includes/site_header.php');
$_GET['prod_ID'];
$product_id = isset($_REQUEST['prod_ID']) ? (int) $_REQUEST['prod_ID'] : 0;
$pound ="&pound;";
?>
<style>
<?php
require('css/prod_details.css');
?>
</style>
<br>
<br>
<br>
<br>
<br>
<?php $product = get_product_details1($freshKickz_conn); ?>

         <?php foreach($product as $productdetails) {
 ?>



<main class="container">

  <!-- Left Column / Headphones Image -->
  <div class="left-column">
    <img data-image="red" class="active" src="<?= htmlspecialchars($productdetails['images']) ?>" style="height: 400px; width: 400px;" alt="">
  </div>
  <!-- Right Column -->
  <div class="right-column">
 
    <!-- Product Description -->
    <div class="product-description">
      <h1><?= htmlspecialchars($productdetails['prod_Name']) ?></h1>
      <p><?= htmlspecialchars($productdetails['prod_Details']) ?></p>
    </div>

    <!-- Product Pricing -->
    <div class="product-price">
      <span><?=$pound?><?= htmlspecialchars($productdetails['prod_Price'])?></span>
      <a href="basket_page.php?quantity=1&action=add_product&name=<?=$productdetails['prod_Name']?>&price=<?=$productdetails['prod_Price']?>" class="cart-btn">Add to Basket</a>
    </div>
    <br>
    <div class="quantity">
        <span>Quantity</span>
        <br>
        <input type="number" min="1" max="9" step="1" value="1">
    </div>
  </div>
</main>
<?php
} ?>
<script src="js/prodJS.js"></script>
<script>
$(document).ready(function () {

    $('.color-choose input').on('click', function () {
        var headphonesColor = $(this).attr('data-image');

        $('.active').removeClass('active');
        $('.left-column img[data-image = ' + headphonesColor + ']').addClass('active');
        $(this).addClass('active');
    });

});
</script>
<?php
require('includes/application_bottom.php');
require('includes/site_footer.php');
?>

这是我的购物篮/结帐页面 -

<?php

require('includes/application_top.php');
$page_title='Your Basket';
require('includes/site_header.php');

if ( ! isset($_SESSION['basket'])) {
  $_SESSION['basket'] = array();
}
$pound ="&pound;";
$action = $_REQUEST['action'] ?? '';
$err = '';

if($_REQUEST['action']=='add_product'){
  $_SESSION['basket'][$_REQUEST['name']]=$_REQUEST['quantity']=$_REQUEST['quantity'];
}

?>
<style>
<?php
require('css/basket.css');
?>
</style>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="row">
  <div class="col-75">
    <div class="container">
      <form action="successful_order.php">

        <div class="row">
          <div class="col-50">
            <h3>Billing Address</h3>
            <label for="fname"><i class="fa fa-user"></i> Full Name</label>
            <input type="text" id="fname" name="firstname" placeholder="John M. Doe">
            <label for="email"><i class="fa fa-envelope"></i> Email</label>
            <input type="text" id="email" name="email" placeholder="john@example.com">
            <label for="adr"><i class="fa fa-address-card-o"></i> Address</label>
            <input type="text" id="adr" name="address" placeholder="542 W. 15th Street">
            <label for="city"><i class="fa fa-institution"></i> City</label>
            <input type="text" id="city" name="city" placeholder="New York">

            <div class="row">
              <div class="col-50">
                <label for="state">County</label>
                <input type="text" id="county" name="county" placeholder="Cheshire">
              </div>
              <div class="col-50">
                <label for="zip">PostCode</label>
                <input type="text" id="postcode" name="postcode" placeholder="SK11 6TF">
              </div>
            </div>
          </div>

          <div class="col-50">
            <h3>Payment</h3>
            <label for="fname">Accepted Cards</label>
            <div class="icon-container">
              <i class="fa fa-cc-visa" style="color:navy;"></i>
              <i class="fa fa-cc-amex" style="color:blue;"></i>
              <i class="fa fa-cc-mastercard" style="color:red;"></i>
              <i class="fa fa-cc-discover" style="color:orange;"></i>
            </div>
            <label for="cname">Name on Card</label>
            <input type="text" id="cname" name="cardname" placeholder="John More Doe">
            <label for="ccnum">Credit card number</label>
            <input type="text" id="ccnum" name="cardnumber" placeholder="1111-2222-3333-4444">
            <label for="expmonth">Exp Month</label>
            <input type="text" id="expmonth" name="expmonth" placeholder="September">

            <div class="row">
              <div class="col-50">
                <label for="expyear">Exp Year</label>
                <input type="text" id="expyear" name="expyear" placeholder="2018">
              </div>
              <div class="col-50">
                <label for="cvv">CVV</label>
                <input type="text" id="cvv" name="cvv" placeholder="352">
              </div>
            </div>
          </div>

        </div>
        <label>
          <input type="checkbox" checked="checked" name="sameadr"> Shipping address same as billing
        </label>
        <input type="submit" value="Checkout" class="btn">
      </form>
    </div>
  </div>

  <div class="col-25">
    <div class="container">
      <h4>Cart
        <span class="price" style="color:black">
          <i class="fa fa-shopping-cart"></i>
        </span>
      </h4>
      <br>
      <br>
      <p><span class="name"><?= $_REQUEST['name'] ?></span> <span class="price"><span class="name"><?= $_REQUEST['quantity'] ?><br></span><?= $pound ?><?= $_REQUEST['price'] ?></span></p>
      <hr>
      <p>Total <span class="price" style="color:black"><b>$30</b></span></p>
    </div>
  </div>
</div>
<?php
require('includes/application_bottom.php');
require('includes/site_footer.php');
?>

【问题讨论】:

  • 我建议阅读minimal, reproducible examples。这里有大量代码需要处理,其中大部分可能与问题无关。缩小您的问题范围,隔离未按预期工作的代码,然后使用 MRE 编辑您的问题。
  • 这听起来很刺耳 - 但看看这段代码,我想说你还没有准备好解决电子商务解决方案,尤其是一个似乎要求卡详细信息的解决方案(因此需要至少通过 PCI 1 级合规性);如果您只是在学习,我会建议一个“更安全”的项目。

标签: php html


【解决方案1】:

首先,您应该避免使用 GET 请求来执行操作。 接下来尝试使用产品 ID,因为不同产品的名称可以相同。

所以我对产品页面的报价:

<?php
require('includes/application_top.php');
$page_title='Details';
require('includes/site_header.php');
$product_id = isset($_REQUEST['prod_ID']) ? (int) $_REQUEST['prod_ID'] : 0;
$pound ="&pound;";
?>
<style>
<?php
require('css/prod_details.css');
?>
</style>
<br>
<br>
<br>
<br>
<br>
<?php $product = get_product_details1($freshKickz_conn); ?>
<?php foreach($product as $productdetails): ?>
    <main class="container">
        <!-- Left Column / Headphones Image -->
        <div class="left-column">
            <img data-image="red" class="active" src="<?= htmlspecialchars($productdetails['images']) ?>" style="height: 400px; width: 400px;" alt="">
        </div>
        <!-- Right Column -->
        <div class="right-column">
            <!-- Product Description -->
            <div class="product-description">
                <h1><?= htmlspecialchars($productdetails['prod_Name']) ?></h1>
                <p><?= htmlspecialchars($productdetails['prod_Details']) ?></p>
            </div>
            <!-- Product Pricing -->
            <form action="basket_page.php" method="POST">
                <div class="product-price">
                    <span><?=$pound?><?= htmlspecialchars($productdetails['prod_Price'])?></span>
                    <input type="hidden" name="action" value="add_product" />
                    <!-- i'm not sure what index did you use for id so -->
                    <input type="hidden" name="id" value="<?php echo htmlspecialchars($productdetails['prod_Name']); ?>" />
                    <input type="hidden" name="price" value="<?php echo htmlspecialchars($productdetails['prod_Price']); ?>" />
                    <input type="hidden" name="name" value="<?php echo htmlspecialchars($productdetails['prod_Name']); ?>" />
                    <button type="submit" class="cart-btn">Add to Basket</button>
                </div>
                <br>
                <div class="quantity">
                    <span>Quantity</span>
                    <br>
                    <input type="number" min="1" max="9" step="1" value="1">
                </div>
           </form>
        </div>
    </main>
<?php endforeach; ?>
<script src="js/prodJS.js"></script>
<script>
$(document).ready(function () {
    $('.color-choose input').on('click', function () {
        var headphonesColor = $(this).attr('data-image');
        $('.active').removeClass('active');
        $('.left-column img[data-image = ' + headphonesColor + ']').addClass('active');
        $(this).addClass('active');
    });
});
</script>
<?php
require('includes/application_bottom.php');
require('includes/site_footer.php');
?>

接下来,您可以在会话中使用关联数组。不要忘记检查所有用户输入。这很重要。

<?php
require('includes/application_top.php');
$page_title = 'Your Basket';
require('includes/site_header.php');

if (!isset($_SESSION['basket'])) {
    $_SESSION['basket'] = [];
}
$pound = "&pound;";
$action = $_REQUEST['action'] ?? '';
$err = '';

if ($action === 'add_product') {
    $id = isset($_POST['id']) ? (int) $_POST['id'] : null;
    $price = isset($_POST['price']) ? (float) $_POST['price'] : null;
    $number = isset($_POST['number']) ? (int) $_POST['number'] : null;
    $name = isset($_POST['name']) ? trim($_POST['name']) : null;
    if ($id && $price && $number) {
        $_SESSION['basket'][$id] = [
            'id' => $id,
            'price' => $price,
            'number' => $number,
            'name' => $name,
        ];
    }
}
?>

接下来,您在渲染时遇到了错误。你应该使用你的会话数组。不是原始输入。

<div class="col-25">
    <div class="container">
        <h4>
            Cart
            <span class="price" style="color:black">
                <i class="fa fa-shopping-cart"></i>
            </span>
        </h4>
        <br>
        <br>
        <?php 
            $total = 0;
            foreach ($_SESSION['basket'] as $item): 
                $total += $item['price'] * $item['number'];
        ?>
            <p>
                <span class="name"><?php echo htmlspecialchars($item['name']) ?></span> 
                <span class="price">
                    <span class="name"><?= $item['number'] ?><br></span>
                    <?= $pound ?><?= $item['price'] ?>
                </span>
            </p>
          <hr>
        <?php endforeach; ?>
        <p>
            Total <span class="price" style="color:black"><b>$<?= total ?></b></span>
        </p>
    </div>
</div>

最后,请查看 WooCommerce 或 Magento 等电子商务的专用 php 脚本。

【讨论】:

  • 您好,我将您所说的添加到我的代码中,它给了我这些错误Warning: Illegal string offset 'price' in C:\MAMP\htdocs\basket_page.php on line 122
  • 您在会话中有旧项目。尝试通过清除浏览器 cookie 来清除会话。
  • 我已经这样做了,但是现在什么都没有添加到购物篮中?
  • 忘记在表单中添加action 参数。固定的。请重试。
猜你喜欢
  • 2012-06-30
  • 2016-05-05
  • 1970-01-01
  • 2020-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-29
相关资源
最近更新 更多