由于您数据库中的列salary_date 是月份类型,因此该列中的数据将存储如下:
2019-01-12
2019-02-01
2019-03-13
我假设一天可以是一个月中的任何一天,而不一定是每个月的第一天。
所以你的Mysql Query应该使用LIKE作为salary_date,应该是这样的
SELECT * FROM `salary` WHERE `salary_employee_id` = '3' AND `salary_date` LIKE '2019-03%'
如果我们假设用户在您的表单中输入月份数。您可以如下更改您的功能
public function checkUser($userid, $month)
{
//$month contains the month number. If it contains Jan, Feb etc change accordingly.
$dateObj = DateTime::createFromFormat('!m', $month);
$m = $dateObj->format('m'); // gives month number with 0 as prefix.
$dateFormat = date('Y') . '-' . $m; //Date Format as used by mysql
$this->db->where('salary_employee_id',$userid);
$this->db->like('salary_date', $dateFormat, 'after'); //Construct Like Condition.
$query=$this->db->get('salary');
if( $query->num_rows() > 0 ) { //If Result Found, return true.
return true;
} else {
return false;
}
}
请注意,这只会检查当前年份。如果要检查前几年或任何特定年份,则需要传递 year 参数
作为该函数的另一个参数。
更新
感谢@Strawberry 的评论,在查询中使用日期范围而不是 LIKE 会更快。所以更新方法如下
public function checkUser($userid, $month)
{
//$inputDate = date('Y-') . $month; //Current Year and given month.
$dateObj = DateTime::createFromFormat('Y-m', $month); //Create Date Object. $month is of format Y-m
$startDate = $dateObj->format('Y-m-01'); // First Date of Month
$endDate = $dateObj->format('Y-m-t'); // Last Date of Month
$this->db->where('salary_employee_id',$userid);
$this->db->where('salary_date >=', $startDate);
$this->db->where('salary_date <=', $endDate);
$query=$this->db->get('salary');
if( $query->num_rows() > 0 ) {
return true;
} else {
return false;
}
}