萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 文章點擊數統計與顯示實作範例

功能需求

實現文章瀏覽次數統計:點擊文章時計數器 +1,顯示頁面時讀取並顯示目前點擊數。支援新聞與案例兩種內容型態。

資料表結構假設

  • gx_news:新聞表,欄位 id, new_hit
  • gx_case:案例表,欄位 id, case_hit

核心函數實作

function newadd($id, $tag, $type) {
    // $tag = 0 更新計數,1 讀取顯示
    // $type = 'news' 或 'case'
    
    $table = ($type === 'news') ? 'gx_news' : 'gx_case';
    $hitField = ($type === 'news') ? 'new_hit' : 'case_hit';
    
    if ($tag == 0) {
        // 更新點擊數
        $sql = "UPDATE `$table` SET `$hitField` = `$hitField` + 1 WHERE `id` = '$id'";
        mysql_query($sql);
    } else {
        // 讀取並顯示點擊數
        $sql = "SELECT `$hitField` FROM `$table` WHERE `id` = '$id'";
        $result = mysql_query($sql);
        $row = mysql_fetch_array($result);
        echo $row[0];
    }
}

使用方式

<?php
// 文章頁面開頭呼叫:更新計數
newadd($article_id, 0, 'news'); 

// 顯示點擊數位置呼叫:讀取顯示
echo "瀏覽次數:";
newadd($article_id, 1, 'news');
?>

安全性與改進建議

  • 棄用 mysql_*:改用 PDO 或 MySQLi 預處理語句防止 SQL 注入
  • 防重複計數:結合 Session/Cookie/IP 限制同一用戶短時間重複計數
  • 效能優化:高流量考慮 Redis/Memcached 快取計數,定期同步資料庫
  • 錯誤處理:加入查詢失敗判斷與日誌記錄

現代化重寫範例(PDO)

function addHit(PDO $pdo, string $table, string $hitField, int $id): void {
    $stmt = $pdo->prepare("UPDATE `$table` SET `$hitField` = `$hitField` + 1 WHERE `id` = ?");
    $stmt->execute([$id]);
}

function getHit(PDO $pdo, string $table, string $hitField, int $id): int {
    $stmt = $pdo->prepare("SELECT `$hitField` FROM `$table` WHERE `id` = ?");
    $stmt->execute([$id]);
    return (int)$stmt->fetchColumn();
}
copyright © 萬盛學電腦網 all rights reserved