如何 select 最后几个月并在 Codeigniter 3 中计算?
How to select last months and calculate in Codeigniter3?
我想在 select 从 db table 日期之后计算 count 变量并从上个月如下函数
问题我已经 select 来自 DB 但我无法检查上个月并计算 count 因为我不想使用 sql 在 CI3 查询中。
这是我的函数
public function last_month() {
$date = date('m', time());
$this->db->select('*');
$this->db->from('user_agent');
$q = $this->db->get();
$count = 0;
if ($q->num_rows() > 0) {
foreach ($q->result() as $item) {
// echo (int)date("m", strtotime($item->timestamp));
if ((int)date("m", strtotime($item->timestamp)) == (int)date("m", strtotime($date))) {
$count += $item->count;
}
}
} else {
return FALSE;
}
return $count;
}
不幸的是,如您所愿 MYSQL 本机函数将是计算此类内容的最佳方式。
如果您想在上面开始时添加月份,例如 9+9+9,那么
SELECT SUM(MONTH(NOW())) AS monthCount FROM `ci_sessions` WHERE `last_activity` > UNIX_TIMESTAMP(STR_TO_DATE("{$currentMonth}", '%Y-%m-%d')) - 1;
,但如果您只想知道适合当前月份的行数,那么
SELECT COUNT(`last_activity`) AS monthCount FROM `ci_sessions` WHERE `last_activity` > UNIX_TIMESTAMP(STR_TO_DATE("{$currentMonth}", '%Y-%m-%d')) - 1;
为了传递上个月的最后一天,您需要在 MySQL 之前在 PHP 中动态使用,例如您应该以这种方式找到它
$currentMonth = date('Y-m-01');
当然,您需要调整代码以适合您的表名和列名。
我想在 select 从 db table 日期之后计算 count 变量并从上个月如下函数
问题我已经 select 来自 DB 但我无法检查上个月并计算 count 因为我不想使用 sql 在 CI3 查询中。
这是我的函数
public function last_month() {
$date = date('m', time());
$this->db->select('*');
$this->db->from('user_agent');
$q = $this->db->get();
$count = 0;
if ($q->num_rows() > 0) {
foreach ($q->result() as $item) {
// echo (int)date("m", strtotime($item->timestamp));
if ((int)date("m", strtotime($item->timestamp)) == (int)date("m", strtotime($date))) {
$count += $item->count;
}
}
} else {
return FALSE;
}
return $count;
}
不幸的是,如您所愿 MYSQL 本机函数将是计算此类内容的最佳方式。 如果您想在上面开始时添加月份,例如 9+9+9,那么
SELECT SUM(MONTH(NOW())) AS monthCount FROM `ci_sessions` WHERE `last_activity` > UNIX_TIMESTAMP(STR_TO_DATE("{$currentMonth}", '%Y-%m-%d')) - 1;
,但如果您只想知道适合当前月份的行数,那么
SELECT COUNT(`last_activity`) AS monthCount FROM `ci_sessions` WHERE `last_activity` > UNIX_TIMESTAMP(STR_TO_DATE("{$currentMonth}", '%Y-%m-%d')) - 1;
为了传递上个月的最后一天,您需要在 MySQL 之前在 PHP 中动态使用,例如您应该以这种方式找到它
$currentMonth = date('Y-m-01');
当然,您需要调整代码以适合您的表名和列名。