購物車是電商系統中不可或缺的核心模組,為消費者提供臨時存放商品的空間。其主要功能涵蓋:商品的新增、刪除、數量變更、單品小計與總價計算、清空購物車,以及後續的訂單生成、列印、預覽、提交與取消等完整流程。
標準操作流程為:用戶登入網站瀏覽商品 → 選擇商品加入購物車 → 在購物車頁面調整數量、刪除商品或繼續購物 → 填寫收件人資訊 → 生成訂單並完成列印、預覽、提交等操作。
Smarty 是以 PHP 開發的模板引擎,核心優勢在於實現「視圖」與「邏輯控制」的分離,即 UI 與 PHP 代碼解耦。由於 PHP 內建不包含 Smarty,需自行下載配置,最低要求 PHP 4.0.6 以上版本。
安裝步驟:
libs 目錄複製至伺服器根目錄,建議重命名為 smartySmarty.class.php、Smarty_Compiler.class.php、Config_File.class.php、debug.tpl,以及 internals 與 plugins 兩個目錄為了多專案複用,慣例將 Smarty 放置於根目錄。需新建四個目錄:
templates - 儲存模板文件templates_c - 儲存編譯後的模板configs - 儲存配置文件cache - 儲存緩存文件建立統一配置文件 config.php,透過 include 引入,避免重複撰寫:
<?php
/* 定義伺服器絕對路徑 */
define('BASE_PATH', 'E:\PHPservices\\');
/* 定義 Smarty 目錄路徑 */
define('SMARTY_PATH', 'SourceCode\12\01\\');
/* 載入 Smarty 類庫 */
require BASE_PATH . SMARTY_PATH . 'smarty\Smarty.class.php';
/* 實例化 Smarty 物件 */
$smarty = new Smarty;
/* 定義各目錄路徑 */
$smarty->template_dir = BASE_PATH . SMARTY_PATH . './';
$smarty->compile_dir = BASE_PATH . SMARTY_PATH . 'templates_c/';
$smarty->config_dir = BASE_PATH . SMARTY_PATH . 'configs/';
$smarty->cache_dir = BASE_PATH . SMARTY_PATH . 'cache/';
/* 定義定界符,避免與前端框架衝突 */
$smarty->left_delimiter = '<{';
$smarty->right_delimiter = '}>';
?>
Smarty 最大特色在於動靜分離。常用技術包含:
使用自定義定界符 <{ 和 }>,結合內建函數:
{section}/{/section},參數 name 與 loop 為必填<{php}>/<{/php}>範例:購物車商品列表渲染
<{if $isShow=="F" }>
<tr>
<td height="22" colspan="5" bgcolor="#FFFFFF">
<div align="center">對不起,您的購物車中暫無商品信息!</div>
</td>
</tr>
<{else}>
<{section name=data loop=$myrow }>
<tr>
<td height="22" align="center" bgcolor="#FFFFFF"><{$myrow[data].tb_commodity_name}></td>
<td height="22" bgcolor="#FFFFFF"><div align="center"><{$myrow[data].tb_commodity_price}></div></td>
</tr>
<{/section}>
<{/if}>
使用 assign() 方法將資料傳遞給模板,display() 指定輸出模板:
$smarty->assign("myrow", $array); // 將陣列資料寫入 myrow
$smarty->display("index.tpl"); // 指定輸出模板頁
利用 Session 變量實現,核心建立兩個 Session 變量:
goodsid - 存儲商品 ID(以 @ 分隔)goodsnum - 存儲商品數量(以 @ 分隔)<?php
session_start();
session_register("goodsid");
session_register("goodsnum");
?>
session_register() 在整個域範圍內註冊 Session 變量,語法:boolean session_register(string name)。
防止重複加入購物車,結合 explode() 與 in_array():
<?php
session_start();
session_register("goodsid");
session_register("goodsnum");
if ($_SESSION["goodsid"]=="" && $_SESSION["goodsnum]=="") {
$_SESSION["goodsid"] = $_GET["id"] . "@";
$_SESSION["goodsnum"] = "1@";
} else {
$array = explode("@", $_SESSION["goodsid"]);
if (in_array($_GET["id"], $array)) {
echo "<script>alert('該商品已經被放入購物車!');history.back();</script>";
exit;
}
$_SESSION["goodsid"] .= $_GET["id"] . "@";
$_SESSION["goodsnum"] .= "1@";
}
echo "<script>window.location.href='shopping_car.php';</script>";
?>
使用 preg_match() 正則驗證,確保輸入為正整數:
$id = $_POST["id"];
$num = $_POST["goodsnum"];
$preg = "/^[0-9]*[0-9]$|^[0-9]*[0-9]$/";
if ($num == "") {
echo "<script>alert('數量不能為空!');history.back();</script>";
exit;
} else if (!preg_match($preg, $num, $str)) {
echo "<script>alert('數量只能為正整數!');history.back();</script>";
exit;
}
執行文件:by_commodity.php。邏輯:建立購物車 → 判斷是否為空 → 空則直接加入 → 非空則檢查重複 → 重複則提示 → 不重複則追加。
執行文件:delete_commodity.php。流程:獲取 ID → explode() 轉陣列 → array_search() 獲取鍵名 → 將對應鍵名設為空 → implode() 重組回 Session。
注意: 刪除後會殘留多餘的 @ 符號(如 "3@2@@")。
優化方案: 改用關聯陣列結構,以商品 ID 為鍵名,值為 "ID,數量" 格式:
<?php
session_register("goods");
$id = $_GET['id'];
$arraygoods = $_SESSION["goods"];
if ($_SESSION["goods"] == "") {
$_SESSION["goods"][$id] = "$id,1";
} else {
if (array_key_exists($id, $_SESSION["goods"])) {
echo "<script>alert('該商品已經被放入購物車!');history.back();</script>";
exit;
}
$_SESSION["goods"][$id] = "$id,1";
}
?>
資料結構示例:[4] => "4,4", [3] => "3,5", [1] => "1,10", [2] => "2,1"
涉及兩個文件:PHP 邏輯文件讀取資料庫、整合資料賦值給 Smarty 變量;模板文件 shopping_dd.tpl 輸出訂單。核心流程:解碼訂單號 → 查詢訂單主檔 → 解析商品 ID 與數量字串 → 逐筆查詢商品明細 → 計算小計與總價 → 整合陣列 → 賦值模板變量(isShow、gnum、myrow、totalprice) → 顯示模板。