如何为不同account_type生成对应URL并输出数据库条目数据?
解决方案:为不同account_type添加对应链接或实现数据筛选
看起来你想要实现两种常见需求之一:要么让每条数据中的account_type字段成为可点击的链接,跳转到对应类型的页面;要么通过页面上的A/B/C链接筛选显示对应类型的数据。我会分别给出两种场景的具体实现代码:
场景1:将每条数据的account_type转为对应链接
如果希望表格里的每个account_type单元格都能点击跳转到accounts.php?type=X,只需要修改循环内的account_type输出部分,把文本包裹成<a>标签即可:
<?php $Qdaily_entriesD = mysqli_query($connect, "SELECT * FROM daily_entries ORDER BY account_type DESC"); while ($showRowGeneral = mysqli_fetch_assoc($Qdaily_entriesD)) { ?> <tr> <!-- 将account_type转为链接,用urlencode处理避免特殊字符导致的URL解析问题 --> <td><a href="accounts.php?type=<?php echo urlencode($showRowGeneral['account_type']); ?>"> <?php echo $showRowGeneral['account_type']; ?> </a></td> <td><?php echo $showRowGeneral['riyal'];?></td> <td><?php echo $showRowGeneral['dollars'];?></td> </tr> <?php } ?> <!-- 可选保留全局筛选链接 --> <tr><td colspan='3'><a href='?type=A'>查看全部A类型</a>, <a href='?type=B'>查看全部B类型</a> or <a href='?type=C'>查看全部C类型</a></td></tr>
场景2:点击链接筛选显示对应类型的数据
如果希望点击页面下方的A/B/C链接后,页面只显示对应类型的数据,需要先处理URL中的筛选参数,再动态构建SQL查询:
<?php // 1. 安全获取并处理筛选参数(防止SQL注入) $selected_type = isset($_GET['type']) ? mysqli_real_escape_string($connect, $_GET['type']) : ''; // 2. 动态构建SQL语句 $sql = "SELECT * FROM daily_entries"; if (!empty($selected_type)) { // 仅当有筛选参数时,添加WHERE条件 $sql .= " WHERE account_type = '$selected_type'"; } $sql .= " ORDER BY account_type DESC"; $Qdaily_entriesD = mysqli_query($connect, $sql); ?> <!-- 表格输出部分 --> <table> <?php while ($showRowGeneral = mysqli_fetch_assoc($Qdaily_entriesD)) { ?> <tr> <td><?php echo $showRowGeneral['account_type'];?></td> <td><?php echo $showRowGeneral['riyal'];?></td> <td><?php echo $showRowGeneral['dollars'];?></td> </tr> <?php } ?> <!-- 筛选链接 --> <tr> <td colspan='3'> <a href='?type=A'>A</a>, <a href='?type=B'>B</a> or <a href='?type=C'>C</a> <!-- 可选添加"显示全部"链接 --> <a href='?' style='margin-left:10px'>显示全部</a> </td> </tr> </table>
重要安全提示
上面的代码用mysqli_real_escape_string()处理了用户输入的参数,能一定程度防止SQL注入。更安全的方式是使用预处理语句,示例如下:
<?php $selected_type = isset($_GET['type']) ? $_GET['type'] : ''; // 使用预处理语句构建查询 $sql = "SELECT * FROM daily_entries"; $params = []; $types = ''; if (!empty($selected_type)) { $sql .= " WHERE account_type = ?"; $params[] = $selected_type; $types = 's'; // s代表字符串类型参数 } $sql .= " ORDER BY account_type DESC"; $stmt = mysqli_prepare($connect, $sql); if (!empty($params)) { mysqli_stmt_bind_param($stmt, $types, ...$params); } mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); ?> <!-- 循环输出数据 --> <?php while ($showRowGeneral = mysqli_fetch_assoc($result)) { ?> <!-- 表格行代码同上 --> <?php } ?>
内容的提问来源于stack exchange,提问作者Iris Tako
相关产品推荐
相关产品推荐

