萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 購物車完整實現:從商品展示到訂單生成

功能模塊劃分

  1. 商品展示頁:圖片、價格、庫存、加入購物車鏈接。
  2. 加入購物車:Session 存儲商品 ID 與數量,登錄攔截、庫存校驗、防重複添加。
  3. 購物車列表:展示商品、修改數量、計算小計/總計、清空/結算。
  4. 訂單生成:收貨信息、付款方式、寫入訂單表/訂單詳情表、清空購物車、庫存扣減。

核心代碼片段

1. 商品展示(簡化)

<?php
// $info 來自數據庫查詢
?>
<table>
  <tr>
    <td rowspan="6"><img src="<?= $info['tupian'] ?: 'noimg.gif' ?>" width="130"></td>
    <td><font color="#EF9C3E">【<?= $info['mingcheng'] ?>】</font></td>
  </tr>
  <tr><td>市場價:<?= $info['shichangjia'] ?></td></tr>
  <tr><td>會員價:<?= $info['huiyuanjia'] ?></td></tr>
  <tr><td><a href="lookinfo.php?id=<?= $info['id'] ?>">查看詳情</a></td></tr>
  <tr><td><a href="addgouwuche.php?id=<?= $info['id'] ?>">加入購物車</a></td></tr>
  <tr><td>庫存:<?= max(0, $info['shuliang'] - $info['cishu']) ?: '售罄' ?></td></tr>
</table>

2. addgouwuche.php — 加入購物車

<?php
session_start();
require 'conn.php';

if (empty($_SESSION['username'])) {
    echo "<script>alert('請先登錄'); history.back();</script>";
    exit;
}

$id = (int)$_GET['id'];
$goods = mysql_fetch_assoc(mysql_query("SELECT * FROM shangpin WHERE id=$id"));
if (!$goods || $goods['shuliang'] <= 0) {
    echo "<script>alert('商品售罄'); history.back();</script>";
    exit;
}

// Session 存儲格式:id1@id2@...  與  qty1@qty2@...
$ids = explode('@', $_SESSION['producelist'] ?? '');
$qtys = explode('@', $_SESSION['quatity'] ?? '');

if (in_array($id, $ids)) {
    echo "<script>alert('已在購物車'); history.back();</script>";
    exit;
}

$_SESSION['producelist'] .= "$id@";
$_SESSION['quatity'] .= "1@";

header("Location: gouwu1.php");
?>

3. gouwu1.php — 購物車列表與操作

<?php
session_start();
if (empty($_SESSION['username'])) { /* 彈窗跳轉 */ }

require 'top.php';
$ids = array_filter(explode('@', $_SESSION['producelist'] ?? ''));
$qtys = array_filter(explode('@', $_SESSION['quatity'] ?? ''));

// 處理操作:更新數量、刪除、清空
if ($_POST['action'] === 'update') {
    foreach ($_POST['qty'] as $i => $q) {
        $qtys[$i] = max(1, (int)$q);
    }
    $_SESSION['quatity'] = implode('@', $qtys) . '@';
} elseif ($_GET['del']) {
    $del = (int)$_GET['del'];
    unset($ids[$del], $qtys[$del]);
    $_SESSION['producelist'] = implode('@', array_values($ids)) . '@';
    $_SESSION['quatity'] = implode('@', array_values($qtys)) . '@';
} elseif ($_GET['clear']) {
    $_SESSION['producelist'] = $_SESSION['quatity'] = '';
}

// 重新查詢商品信息
$total = 0;
echo "<form method='post'><table>";
foreach ($ids as $i => $gid) {
    $g = mysql_fetch_assoc(mysql_query("SELECT * FROM shangpin WHERE id=$gid"));
    if (!$g) continue;
    $subtotal = $g['huiyuanjia'] * $qtys[$i];
    $total += $subtotal;
    echo "<tr>
        <td>{$g['mingcheng']}</td>
        <td>{$g['huiyuanjia']}</td>
        <td><input name='qty[$i]' value='{$qtys[$i]}' size=3></td>
        <td>$subtotal</td>
        <td><a href='?del=$i'>刪除</a></td>
    </tr>";
}
echo "<tr><td colspan=4>總計:$total</td><td><input type='submit' name='action' value='update'> <a href='?clear=1'>清空</a></td></tr>";
echo "</table></form>";
echo "<a href='order.php'>去結算</a>";
?>

安全與擴展提示

  • 所有 SQL 參數必須經 intval 或預處理防注入。
  • Session 數據結構簡單,大型項目建議改用數據庫表 cart(user_id, goods_id, qty, add_time)。
  • 並發下單需引入事務與行鎖(SELECT ... FOR UPDATE)防止超賣。
  • 引入 CSRF Token 保護表單提交。
copyright © 萬盛學電腦網 all rights reserved