You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP商城商品跳转时传递商品ID的实现方案咨询

解决商品ID传递问题的方法

一、基础实现:通过GET请求传递商品ID

这是最直接且常用的方式,利用URL查询字符串传递参数。

1. 修改index.php的商品链接

在index.php中,为每个商品生成携带ID的跳转链接:

// 假设从数据库取出商品列表,循环生成每个商品的展示项
foreach ($products as $product) {
    echo '<div class="product-card">';
    echo '<h4>' . htmlspecialchars($product['name']) . '</h4>';
    // 链接中拼接商品ID参数
    echo '<a href="info.php?id=' . $product['id'] . '">查看详情</a>';
    echo '</div>';
}

点击链接后会跳转到info.php?id=xxx(xxx为对应商品的ID)。

2. 在info.php中接收并使用ID

无需包含index.php,直接从$_GET全局数组获取ID,同时做安全校验:

// 校验ID是否存在且为有效整数(假设ID是整数类型)
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($id <= 0) {
    echo '无效的商品ID';
    exit;
}

// 用$id查询数据库获取商品信息(使用预编译语句防止SQL注入)
$pdo = new PDO('mysql:host=localhost;dbname=your_mall_db', 'username', 'password');
$stmt = $pdo->prepare('SELECT * FROM products WHERE id = ?');
$stmt->execute([$id]);
$product = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$product) {
    echo '该商品不存在';
    exit;
}

// 渲染商品详情页面
echo '<h1>' . htmlspecialchars($product['name']) . '</h1>';
echo '<img src="' . htmlspecialchars($product['image_path']) . '" alt="' . htmlspecialchars($product['name']) . '">';
echo '<p>' . htmlspecialchars($product['description']) . '</p>';

二、更高效的传参与优化方式

1. 强化GET请求的安全性

  • 严格校验参数类型:比如强制转换为整数,过滤非法字符;
  • 必须使用预编译语句查询数据库,杜绝SQL注入风险;
  • 校验ID对应的商品是否存在,避免无效请求返回错误页面。

2. 美化URL(提升体验与SEO)

通过服务器重写规则将info.php?id=123转为更友好的/product/123:

  • Apache环境:在项目根目录创建.htaccess文件:
RewriteEngine On
RewriteRule ^product/(\d+)$ info.php?id=$1 [L]

之后商品链接可改为<a href="/product/' . $product['id'] . '">查看详情</a>。

  • Nginx环境:在配置文件中添加规则:
location /product {
    rewrite ^/product/(\d+)$ /info.php?id=$1 last;
}

3. 分离公共代码(避免冗余)

如果两个页面需要共享头部、导航栏等布局,抽离公共部分为单独文件(如header.php、footer.php),在页面中分别引入:

// 在info.php顶部引入公共头部
include 'header.php';

// 中间是商品详情逻辑

// 底部引入公共尾部
include 'footer.php';

内容的提问来源于stack exchange,提问作者NFT_king

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 05:22:26