簡體   English   中英

每天計算總數php

[英]Count total posts each day php

我有一個功能,可以統計整個網站上的帖子總數

function posts_count(){ 
$data=mysql_fetch_assoc(mysql_query("SELECT count(*) as total from posts"));
return $data['total'];

}

我如何計算每天發布了多少新帖子? 例如,今天的新帖子總數:55

我在想,因為發布帖子時數據庫中有日期行,所以我可以做類似的事情

function posts_count_today(){   
    $data=mysql_fetch_assoc(mysql_query("SELECT count(*) as total from posts WHERE date = '$date_today'"));
    return $data['total'];
}

其中$ date_today顯然是當前日期,但是我敢肯定有一個更好的功能,例如now()或類似的東西

是的,立即使用是個好主意。 如果您的日期列還包含時間部分,請考慮使用DATE函數:

SELECT count(*) as total from posts WHERE DATE(date) = DATE(NOW())

無論何時,這都將獲取今天發布的所有帖子。

您的表中是否有一欄記錄創建日期? 這是帶有該表格的示例:

create table foo( foo_id int NOT NULL AUTO_INCREMENT, recorded TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP );

recorded列永遠不能由程序填充。 將其保留為空白將意味着該記錄將具有輸入記錄的時間戳。

然后,您可以根據recorded列選擇所有行。

function posts_count_today(){   
    $data=mysql_fetch_assoc(mysql_query("
      SELECT count(*) as total 
      FROM posts 
      WHERE recorded > '$date_today'
    ")); //<== $date_today will have to be a format mysql understands. Can't remember off the top of my head but should be google-able.

    return $data['total'];
}

要獲取數據庫帖子記錄中EACH DAY的帖子數和日期,請嘗試以下操作:

SELECT count(DATE(`date`)) as total,
DATE(`date`) as distinctDate
FROM posts
WHERE DATE(date) <= DATE(NOW())
GROUP BY DATE(`date`)

試試這個SQL

select count(*) as count, date from posts group by date

PHP代碼

$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
  $data[$row['date']] = $row['count'];
}

如果您每天都看到計數發布,則可以使用以下查詢:

選擇計數(*),按日期分組

但是此查詢返回到多行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM