如何从数据库获取上周和上个月的注册用户

时间:2018-07-25 16:18:42

标签: php sql database pdo

我有一个表格,其中有我要获取上周和上个月的注册用户的用户注册日期列,但不知道它将如何工作。以下是其他有效的查询:

$users_today = $db_con->query("SELECT COUNT(*) as reg_date FROM users WHERE DATE(reg_date) = CURDATE()")->fetchColumn();
$users_yesterday = $db_con->query("SELECT COUNT(*) as reg_date FROM users WHERE reg_date=SUBDATE(CURDATE(), 1)")->fetchColumn();
$users_this_week = $db_con->query("SELECT COUNT(*) as reg_date FROM users WHERE WEEK(reg_date) = WEEK(CURRENT_DATE())")->fetchColumn();
$users_month = $db_con->query("SELECT COUNT(*) as reg_date FROM users WHERE MONTH(reg_date) = MONTH(CURRENT_DATE())")->fetchColumn();
$users_year = $db_con->query("SELECT COUNT(*) as reg_date FROM users WHERE YEAR(reg_date) = YEAR(CURRENT_DATE())")->fetchColumn();
$users_total = $db_con->query('SELECT COUNT(*) FROM users')->fetchColumn(); 

一周从星期一开始。 并且请让我知道这些查询是否可以安全使用(避免SQL漏洞),或者是否有其他更好的建议可以确保这些安全。

1 个答案:

答案 0 :(得分:0)

如果您将last week定义为今天之前的7天:

$users_last_week = $db_con->query("SELECT COUNT(*) as reg_date 
  FROM users 
  WHERE reg_date BETWEEN DATE_SUB(CURRENT_DATE(), INTERVAL 7 DAY)
  AND DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)")->fetchColumn();

如果您将last week定义为最近的7天,从星期一开始,到星期日结束,并且其中任何一个都在今天之前:

$users_last_week = $db_con->query("SELECT COUNT(*) as reg_date 
  FROM users 
  WHERE reg_date BETWEEN SUBDATE(CURRENT_DATE(), INTERVAL 7 + WEEKDAY(CURRENT_DATE()) DAY)
  AND SUBDATE(CURRENT_DATE(), INTERVAL 1+WEEKDAY(CURRENT_DATE()) DAY)")->fetchColumn();

如果您将last month定义为今天之前的30天:

$users_last_month = $db_con->query("SELECT COUNT(*) as reg_date 
  FROM users 
  WHERE reg_date BETWEEN DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY)
  AND DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)")->fetchColumn();

如果您将last month定义为当前月份之前的日历月:

$users_last_month = $db_con->query("SELECT COUNT(*) as reg_date 
  FROM users 
  WHERE reg_date BETWEEN DATE_SUB(DATE_SUB(CURRENT_DATE(), INTERVAL DAY(CURRENT_DATE())-1 DAY), INTERVAL 1 MONTH)
  AND DATE_SUB(CURRENT_DATE(), INTERVAL DAY(CURRENT_DATE()) DAY)")->fetchColumn();

更新

关于错误结果的说明-在上周的右边界删除了1天,在上个月的左边界添加了1天。

更新2

仅获取当前一周的注册:

$users_this_week = $db_con->query("SELECT COUNT(*) as reg_date 
  FROM users 
  WHERE reg_date BETWEEN SUBDATE(CURRENT_DATE(), INTERVAL WEEKDAY(CURRENT_DATE()) DAY)
  AND CURRENT_DATE()")->fetchColumn();