You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

热门文章系统:如何用SQL获取近8小时TOP10浏览量ID

嘿,我来帮你搞定这个热门文章检索的需求~首先得说,你的现有代码有两个关键问题需要优化:一是存在SQL注入风险,二是目前没有记录数据更新/插入时间的字段——这会导致你根本没法筛选出过去8小时内的有效数据。咱们一步步来解决:

第一步:给数据表添加时间追踪字段

你需要给top_pages表新增一个自动维护的时间字段,用来记录每条数据的最后更新时间。执行这条SQL语句即可:

ALTER TABLE top_pages ADD COLUMN updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;

这个字段会在插入新记录时自动设为当前时间,每次更新total_views时也会自动刷新为当前时间,完美满足你筛选时间范围的需求。

第二步:优化现有计数代码(解决SQL注入+适配时间字段)

你的现有代码直接把$id拼进SQL语句里,很容易被SQL注入攻击。换成预处理语句不仅更安全,还不用手动维护updated_at(因为字段已经设置了自动更新逻辑):

$servername = "";
$username = "";
$password = "";
$dbname = "";

$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$id = '44441';
// 预处理语句检查记录是否存在
$checkStmt = mysqli_prepare($conn, "SELECT id FROM top_pages WHERE id = ?");
mysqli_stmt_bind_param($checkStmt, "s", $id);
mysqli_stmt_execute($checkStmt);
mysqli_stmt_store_result($checkStmt);

if (mysqli_stmt_num_rows($checkStmt) > 0) {
    echo 'exist';
    // 更新浏览量,updated_at会自动更新
    $updateStmt = mysqli_prepare($conn, "UPDATE top_pages SET total_views = total_views + 1 WHERE id = ?");
    mysqli_stmt_bind_param($updateStmt, "s", $id);
    mysqli_stmt_execute($updateStmt);
} else {
    echo 'not found';
    // 插入新记录,updated_at自动设为当前时间
    $insertStmt = mysqli_prepare($conn, "INSERT INTO top_pages (id, total_views) VALUES (?, 1)");
    mysqli_stmt_bind_param($insertStmt, "s", $id);
    mysqli_stmt_execute($insertStmt);
}

// 关闭语句和连接
mysqli_stmt_close($checkStmt);
isset($updateStmt) && mysqli_stmt_close($updateStmt);
isset($insertStmt) && mysqli_stmt_close($insertStmt);
mysqli_close($conn);
第三步:检索过去8小时的前10热门ID

现在有了updated_at字段,就可以轻松筛选出过去8小时内的数据,并按浏览量排序取前10。对应的SQL查询和PHP代码示例如下:

SQL查询语句

SELECT id, total_views 
FROM top_pages 
WHERE updated_at >= DATE_SUB(NOW(), INTERVAL 8 HOUR)
ORDER BY total_views DESC
LIMIT 10;

对应的PHP实现代码

// 数据库连接(和上面的连接逻辑一致)
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// 执行热门数据查询
$sql = "SELECT id, total_views 
        FROM top_pages 
        WHERE updated_at >= DATE_SUB(NOW(), INTERVAL 8 HOUR)
        ORDER BY total_views DESC
        LIMIT 10";
$result = mysqli_query($conn, $sql);

// 处理并输出结果
if (mysqli_num_rows($result) > 0) {
    echo "过去8小时热门文章Top 10:<br>";
    while($row = mysqli_fetch_assoc($result)) {
        echo "文章ID: " . $row["id"]. " - 浏览量: " . $row["total_views"]. "<br>";
    }
} else {
    echo "过去8小时暂无热门数据";
}

mysqli_close($conn);

内容的提问来源于stack exchange,提问作者magix01

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:31:10