PHP电商共用单商品详情页 点击商品加载对应数据实现方法
单商品详情页通用实现方案
核心实现逻辑:通过URL传递商品唯一标识,详情页接收标识后从数据库拉取对应商品数据渲染,全程只需要一个详情页文件,分三步改完即可:
1. 改造商品列表跳转规则
你当前的跳转逻辑没有携带商品标识,所以详情页不知道要加载哪个商品。
注意:必须用商品表的自增主键
id作为商品唯一标识,不要用商品名传参,避免重名、特殊字符转义问题。
如果你现在是静态写死的商品卡片,测试阶段可以先手动给每个商品分配对应数据库ID,修改跳转地址:
<!-- 第一个商品对应数据库id=1 --> <div class="col-1" onclick="location.href='item1.php?id=1';" style="cursor: pointer;"> <img src="Images/products/rooster18.png" alt="Rooster Chicken #18"> <h4>Rooster Chicken #18</h4> <p>$17.65 <strike> $17.80 </strike></p> </div> <!-- 第二个商品对应数据库id=2 --> <div class="col-1" onclick="location.href='item1.php?id=2';" style="cursor: pointer;"> <img src="Images/products/rewa full cream milk 1L Net.png" alt="rewa full cream milk 1L Net"> <h4>REWA Full Cream Milk 1L Net</h4> <p>$2.52 <strike> $3.30 </strike></p> </div>
后续你把商品列表改成PHP循环动态输出时,直接把ID替换成查询结果里的商品ID字段即可,示例写法:
<div class="col-1" onclick="location.href='item1.php?id=<?= $item['id'] ?>';" style="cursor: pointer;"> <img src="Images/products/<?= htmlspecialchars($item['cover']) ?>" alt="<?= htmlspecialchars($item['name']) ?>"> <h4><?= htmlspecialchars($item['name']) ?></h4> <p>$<?= number_format($item['current_price'],2) ?> <strike> $<?= number_format($item['origin_price'],2) ?> </strike></p> </div>
2. 编写item1.php的数据拉取逻辑
在item1.php顶部加入基础校验、数据查询逻辑,先做合法性判断再查库,避免无效查询和报错:
<?php session_start(); include("connection.php"); include("functions.php"); $user_data = check_login($con); // 校验商品ID合法性 if (!isset($_GET['id']) || !is_numeric($_GET['id']) || intval($_GET['id']) <= 0) { header("Location: index.php"); // ID非法直接跳回首页 exit; } $goods_id = intval($_GET['id']); // 用预处理语句查询商品信息,防SQL注入 $stmt = mysqli_prepare($con, "SELECT * FROM goods WHERE id = ? LIMIT 1"); mysqli_stmt_bind_param($stmt, "i", $goods_id); mysqli_stmt_execute($stmt); $res = mysqli_stmt_get_result($stmt); $goods = mysqli_fetch_assoc($res); if (!$goods) { header("Location: index.php"); // 商品不存在跳回首页/404 exit; } ?>
必须使用mysqli预处理语句做查询,禁止直接拼接SQL字符串,避免SQL注入风险
3. 在item1.php中渲染商品详情
查询到的$goods数组包含当前商品的所有字段,直接在页面对应位置输出即可:
<div class="product-detail"> <div class="detail-img"> <img src="Images/products/<?= htmlspecialchars($goods['cover']) ?>" alt="<?= htmlspecialchars($goods['name']) ?>"> </div> <div class="detail-info"> <h1><?= htmlspecialchars($goods['name']) ?></h1> <div class="price-row"> <span class="current-price">$<?= number_format($goods['current_price'],2) ?></span> <strike class="origin-price">$<?= number_format($goods['origin_price'],2) ?></strike> </div> <div class="stock">库存:<?= $goods['stock'] ?></div> <div class="desc"> <?= htmlspecialchars($goods['description']) ?> </div> <!-- 加购、下单按钮等其他模块按需扩展即可 --> </div> </div>
补充说明
- 所有从数据库读取后输出到HTML的内容,都要用
htmlspecialchars()处理,避免XSS攻击 - 全站所有商品跳转入口(搜索结果、推荐位、分类页、购物车商品入口等),统一跳转到
item1.php?id=对应商品ID即可,不需要新增其他详情页文件 - 如果需要实现商品浏览历史功能,在item1.php拿到合法
$goods_id后,把ID存入session/cookie的浏览记录数组即可
内容的提问来源于stack exchange,提问作者zamceaser
相关产品推荐
相关产品推荐

