如何通过PHP和MySQL动态将页面标题与商品标题匹配
实现商品详情页标题动态显示商品名称的方法
要让details.php的页面标题显示对应商品名称,只需在详情页中先获取当前商品的标题,再动态赋值给$title变量即可,具体步骤如下:
1. 在details.php中获取商品ID并查询对应数据
详情页通过details.php?id=商品ID的方式接收参数,先获取这个ID,再从数据库中查询该商品的标题:
<?php // 确保已连接数据库(若head.php未包含数据库连接代码,需自行引入连接文件) include('path/to/your/db-connection.php'); // 获取URL中的商品ID并做基础校验 $product_id = isset($_GET['id']) ? $_GET['id'] : 0; $product_id = mysqli_real_escape_string($con, $product_id); // 基础SQL注入防护 // 查询对应商品的标题 $sql = "SELECT title FROM product_tbl WHERE id = '$product_id'"; $result = mysqli_query($con, $sql); // 初始化默认标题 $title = "TBROS | 商品详情"; if ($result && mysqli_num_rows($result) > 0) { $row = mysqli_fetch_assoc($result); $pro_title = $row['title']; // 动态设置页面标题 $title = "TBROS | {$pro_title}"; } // 必须在$title赋值完成后引入head.php include('partials/head.php'); ?>
2. 确保head.php中的正确使用$title变量 <a class="header-anchor" href="#_2-确保head-php中的正确使用-title变量" aria-hidden="true">#</a></h2>
<p>你的<code>head.php</code>里的<code><title></code>标签应如下编写,保证能正确输出动态标题:</p>
<pre class="hljs"><code class="language-html volc-pre-code"><title><?php echo isset($title) ? $title : 'TBROS'; ?></title>
</code></pre>
<h2 id="注意事项">注意事项 <a class="header-anchor" href="#注意事项" aria-hidden="true">#</a></h2>
<ul>
<li><strong>强化SQL注入防护</strong>:上述代码用<code>mysqli_real_escape_string</code>做了基础处理,更安全的方式是使用mysqli预处理语句:</li>
</ul>
<pre class="hljs"><code class="language-php volc-pre-code">// 预处理语句示例
$stmt = mysqli_prepare($con, "SELECT title FROM product_tbl WHERE id = ?");
mysqli_stmt_bind_param($stmt, "i", $product_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
</code></pre>
<ul>
<li><strong>处理商品不存在场景</strong>:如果查询不到对应ID的商品,页面会显示默认标题,你也可以将默认标题改为"商品不存在"这类提示信息。</li>
</ul>
<p>内容的提问来源于stack exchange,提问作者NASSER 95</p>
相关产品推荐
相关产品推荐

