在電商網站開發中,購物車是核心功能之一。本文提供一個不依賴資料庫、純使用 PHP Session 與 JavaScript AJAX 實作的簡易購物車範例,適合初學者快速理解運作邏輯,並作為進階開發的基礎雛形。
我們封裝一個 Shopcar 類別來管理商品清單,主要功能包括檢查商品是否存在、新增商品、刪除商品與顯示清單。商品資料結構包含名稱、數量與價格,儲存於陣列屬性 $productList 中。
<?php
class Shopcar {
public $productList = array();
// 檢查商品是否已在購物車
public function checkProduct($product) {
for ($i = 0; $i < count($this->productList); $i++) {
if ($this->productList[$i]['name'] == $product['name']) {
return $i;
}
}
return -1;
}
// 新增商品至購物車
public function add($product) {
$i = $this->checkProduct($product);
if ($i == -1) {
array_push($this->productList, $product);
} else {
$this->productList[$i]['num'] += $product['num'];
}
}
// 刪除商品
public function delete($product) {
$i = $this->checkProduct($product);
if ($i != -1) {
array_splice($this->productList, $i, 1);
}
}
// 取得所有商品
public function show() {
return $this->productList;
}
}
?>
前端頁面列出商品,使用者輸入數量點擊「購買」時,透過 jQuery AJAX 將商品資訊 POST 到 index.php。注意:此處使用 label 標籤儲存名稱與價格,實務上建議改用 data-* 屬性或隱藏輸入框。
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function buy(i) {
var num = $(':input[name=num]')[i].value;
var name = $('[name=name]')[i].innerHTML;
var price = $('[name=price]')[i].innerHTML;
$.ajax({
type: 'post',
url: 'index.php',
cache: false,
data: 'num=' + num + '&name=' + name + '&price=' + price,
success: function(data) {
alert(data); // 實務上可回傳 JSON 並更新頁面顯示
}
});
}
</script>
接收 AJAX 資料,啟動 Session,將商品物件序列化存入 $_SESSION['shopcar']。若 Session 已存在購物車物件則反序列化繼續使用,否則實例化新物件。
<?php
require 'Shopcar.class.php';
session_start();
$name = $_POST['name'];
$num = $_POST['num'];
$price = $_POST['price'];
$product = array('name' => $name, 'num' => $num, 'price' => $price);
if (isset($_SESSION['shopcar'])) {
$shopcar = unserialize($_SESSION['shopcar']);
} else {
$shopcar = new Shopcar();
}
$shopcar->add($product);
$_SESSION['shopcar'] = serialize($shopcar);
?>
反序列化 Session 中的購物車物件,遍歷商品清單並以表格顯示。
<?php
require 'Shopcar.class.php';
session_start();
$shopcar = unserialize($_SESSION['shopcar']);
$productList = $shopcar->productList;
?>
<table>
<tr><td>商品編號</td><td>商品名稱</td><td>價格</td><td>數量</td></tr>
<?php foreach ($productList as $product) { ?>
<tr>
<td>1</td>
<td><label><?php echo $product['name']; ?></label></td>
<td><label><?php echo $product['price']; ?></label></td>
<td><input name='num' type='text' value='<?php echo $product['num']; ?>' /></td>
</tr>
<?php } ?>
</table>
num 為正整數、price 為數值,防止惡意竄改。htmlspecialchars() 轉義。{success: true, count: 3}),前端動態更新購物車圖示數量,體驗更佳。cart 資料表,欄位包含 user_id、product_id、quantity、created_at 等。此範例展示了 PHP 物件導向、Session 管理與前後端 AJAX 互動的基本整合。雖然功能簡單,但掌握核心流程後,即可擴充為具備優惠碼、庫存檢查、多規格選擇等完整電商級購物車系統。