實現文章瀏覽次數統計:點擊文章時計數器 +1,顯示頁面時讀取並顯示目前點擊數。支援新聞與案例兩種內容型態。
gx_news:新聞表,欄位 id, new_hitgx_case:案例表,欄位 id, case_hitfunction 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');
?>
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();
}