如何在两个PHP页面间传递静态数据,实现点击条目跳转展示对应详情
实现方案
第一步:修改results.php中条目的跳转链接
通过GET参数传递条目名称是当前场景下最简单的实现方式,不需要额外加表单控件,直接在跳转URL后缀拼接参数即可。
仅需要调整$link变量的赋值逻辑,将你需要传递的条目标题(也就是代码中的$row[0])经过URL编码后作为参数拼接在details.php后面即可,其余代码不需要改动:
function showAsItem($row) { $defaultValue = $row[1]; $itemClassname="item"; $titleClassname="title"; $imageClassname="image"; $infoClassname="infolist"; // 新增参数拼接逻辑,urlencode用于处理特殊字符避免链接异常 $link = "details.php?item_name=" . urlencode($row[0]); $target="_top"; $img="https://barcelonando.com/es/wp-content/uploads/2012/12/barceloneta.jpg"; $alt="Imagen de $row"; echo '<div class="'.$itemClassname.'">'; echo '<div class="' .$titleClassname. '">'; echo '<a href="'.$link.'" target="' .$target. '">' .ucfirst($row[0]). '</a>'; echo '</div>'; echo '<div class="' .$imageClassname. '">'; echo '<a href="' .$link. '" target="' .$target. '">'; echo '<img src="' .$img. '" alt="' .$alt. '"/>'; echo '</a>'; echo '</div>'; echo '<div class="' .$infoClassname. '">'; echo '<ul>'; echo '<li> Población: ' .$row[1]. '</li>'; echo '<li> Esperanza de vida: ' .$defaultValue. '</li>'; echo '<li> Inmigrantes: ' .$defaultValue. '</li>'; echo '<li> Transportes: ' .$defaultValue. '</li>'; echo '<li> Accidentes: ' .$defaultValue. '</li>'; echo '</ul>'; echo '</div>'; echo '</div>'; }
第二步:在details.php中接收并处理传递的参数
通过PHP全局变量$_GET即可拿到传递的条目名称,建议加上参数校验和安全过滤,避免异常报错和安全风险,参考代码如下:
<?php // 判断参数是否存在,不存在的话可以跳回列表页或者提示错误 if (!isset($_GET['item_name'])) { header('Location: results.php'); exit; } // 接收参数并做基础处理 $item_name = trim($_GET['item_name']); // 如果后续需要用这个参数查询数据库,必须使用预处理语句,避免SQL注入 // 如果需要直接把条目名输出到页面,使用htmlspecialchars转义特殊字符,防止XSS攻击 $safe_output_name = htmlspecialchars($item_name); // 后续就可以用$item_name查询对应条目详情,渲染页面即可 echo "当前查看的条目:" . $safe_output_name; // 其他详情查询、渲染逻辑... ?>
内容的提问来源于stack exchange,提问作者Juan Andres Flores Gutierrez
相关产品推荐
相关产品推荐

