MySQL/PHP:实现统计查询结果跳转展示单用户通话详情
实现点击呼叫方查看详细通话记录的方案
要完成你想要的功能,只需要两步:给列表链接添加用户标识参数,然后在total.php中接收参数并查询对应数据。
1. 修改原页面的链接,传递呼叫方参数
原代码里的链接没有传递任何用户信息,所以total.php不知道要展示谁的记录。我们需要把call_from的值作为GET参数附在链接后面,还要用urlencode()处理特殊字符避免传递异常:
// 原链接部分修改为: echo ' <tr> <td><a href="total.php?call_from='.urlencode($row['call_from']).'">'. $row['call_from'] .'</a></td> <td>'. $row['COUNT(id)'] .'</td> <td>'. $row['ROUND(SUM(cost), 2)'] .'</td> </tr> ';
另外建议你给SQL查询的聚合字段起别名,这样代码可读性更好,比如:
SELECT id, COUNT(id) AS call_count, call_from, ROUND(SUM(cost), 2) AS total_cost FROM calls GROUP BY call_from ORDER BY call_count DESC;
之后输出的时候就可以用$row['call_count']和$row['total_cost'],比$row['COUNT(id)']更直观。
2. 编写total.php页面的代码
在这个页面里,我们需要接收传递过来的call_from参数,然后查询该用户的所有通话记录,同时要注意SQL注入防护,必须用预处理语句来执行查询:
<?php // 1. 连接数据库 $conn = mysqli_connect("localhost", "daven", "H3x^g0n", "Telcel"); if (!$conn) { die("数据库连接失败: " . mysqli_connect_error()); } // 2. 接收并验证参数 if (!isset($_GET['call_from']) || empty($_GET['call_from'])) { echo "<p>请选择一个有效的呼叫方</p>"; exit; } $call_from = urldecode($_GET['call_from']); // 解码传递的参数 // 3. 用预处理语句查询数据,防止SQL注入 $query = "SELECT id, call_from, call_to, date_time, duration, cost, status FROM calls WHERE call_from = ?"; $stmt = mysqli_prepare($conn, $query); mysqli_stmt_bind_param($stmt, "s", $call_from); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); // 4. 展示数据 ?> <!DOCTYPE html> <html> <head> <title><?php echo htmlspecialchars($call_from); ?>的通话记录</title> <style> table { border-collapse: collapse; } th, td { border: 1px solid #ddd; padding: 8px; } th { background-color: #f2f2f2; } </style> </head> <body> <h1><?php echo htmlspecialchars($call_from); ?>的所有通话记录</h1> <table> <tr> <th>通话ID</th> <th>呼叫方</th> <th>被叫方</th> <th>通话时间</th> <th>时长</th> <th>费用</th> <th>状态</th> </tr> <?php if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { echo "<tr>"; echo "<td>".htmlspecialchars($row['id'])."</td>"; echo "<td>".htmlspecialchars($row['call_from'])."</td>"; echo "<td>".htmlspecialchars($row['call_to'])."</td>"; echo "<td>".htmlspecialchars($row['date_time'])."</td>"; echo "<td>".htmlspecialchars($row['duration'])."</td>"; echo "<td>".htmlspecialchars($row['cost'])."</td>"; echo "<td>".htmlspecialchars($row['status'])."</td>"; echo "</tr>"; } } else { echo "<tr><td colspan='7'>暂无该用户的通话记录</td></tr>"; } ?> </table> </body> </html> <?php // 关闭连接 mysqli_stmt_close($stmt); mysqli_close($conn); ?>
关键注意点
- 用
urlencode()和urldecode()处理参数,避免特殊字符(比如空格、特殊符号)导致参数传递错误 - 必须使用预处理语句执行查询,杜绝SQL注入风险
- 用
htmlspecialchars()输出用户数据,防止XSS攻击
内容的提问来源于stack exchange,提问作者Thomas Crown
相关产品推荐
相关产品推荐

