如何实现博客预览动态跳转至view_post.php?及该页面编写方法
实现博客文章预览的动态链接及详情页开发
一、修改主页面的动态链接
你的现有代码里,文章预览的链接是静态的view_post.php,我们需要把文章的id作为参数拼接到链接里,这样点击不同的预览就能跳转到对应文章的详情页。
修改你代码中的PHP循环部分,调整a标签的href属性,同时优化预览内容的显示(原来的代码把id直接展示了,换成标题+作者+正文预览会更合理):
<?php $sql = "SELECT id, title, author, body FROM posts ORDER BY id DESC"; if ($result = mysqli_query($con, $sql)) { // 逐行获取文章数据 while ($row = mysqli_fetch_row($result)) { // 把文章id拼接到链接中,同时显示标题、作者和正文预览 printf( '<a href="view_post.php?id=%s"><div class="row"><div class="row-inner"><p><strong>%s</strong> | %s</p><p>%s...</p></div></div></a>', $row[0], // 文章id,用于生成动态链接 $row[1], // 文章标题 $row[2], // 文章作者 substr($row[3], 0, 150) // 截取正文前150字符作为预览 ); } mysqli_free_result($result); } mysqli_close($con); ?>
这里的关键改动是把静态链接view_post.php改成了view_post.php?id=%s,%s会被当前文章的id替换,最终生成类似view_post.php?id=1的动态链接。
二、编写view_post.php的内容
详情页需要完成参数验证、数据库查询、内容展示三个核心步骤,以下是完整的代码示例:
<?php session_start(); require_once('required/db.php'); // 第一步:验证id参数是否合法 if (!isset($_GET['id']) || !is_numeric($_GET['id'])) { echo "<h2>无效的文章ID</h2><p><a href='index.php'>返回博客首页</a></p>"; exit; } $postId = (int)$_GET['id']; // 第二步:用预处理语句查询对应文章(防止SQL注入) $sql = "SELECT title, author, body, created_at FROM posts WHERE id = ?"; $stmt = mysqli_prepare($con, $sql); mysqli_stmt_bind_param($stmt, "i", $postId); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); // 处理文章不存在的情况 if (mysqli_num_rows($result) === 0) { echo "<h2>未找到该文章</h2><p><a href='index.php'>返回博客首页</a></p>"; exit; } $post = mysqli_fetch_assoc($result); ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1"> <title><?php echo htmlspecialchars($post['title']); ?> - WillWam Blog</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="assets/css/style.css" type="text/css"> <link rel="ico" href="assets/favicon.ico"> </head> <body> <nav><h2 class="title"><a href="index.php">The Blog</a></h2></nav> <div class="wrapper container"> <h1><?php echo htmlspecialchars($post['title']); ?></h1> <p class="meta">作者: <?php echo htmlspecialchars($post['author']); ?></p> <div class="post-content"> <?php echo nl2br(htmlspecialchars($post['body'])); ?> </div> <p><a href="index.php">返回博客首页</a></p> </div> </body> </html> <?php mysqli_stmt_close($stmt); mysqli_close($con); ?>
这个详情页做了这些实用处理:
- 参数校验:确保
id存在且为有效数字,避免无效请求 - 安全防护:使用预处理语句查询数据库,彻底防止SQL注入
- 错误处理:如果文章不存在,显示友好提示并引导返回首页
- 内容安全:用
htmlspecialchars()转义所有输出内容,防止XSS攻击 - 排版优化:用
nl2br()把文章中的换行转换成HTML的<br>标签,保证正文排版正常
内容的提问来源于stack exchange,提问作者Will Hoffman
相关产品推荐
相关产品推荐

