gpt4 book ai didi

php - Codeigniter- 检查用户在一个月内是否存在

转载 作者:行者123 更新时间:2023-11-30 21:27:58 25 4
gpt4 key购买 nike

我们如何在 codeigniter 中检查本月(从提交表单获取的月份)的用户退出情况

例如:有一种叫做工资计算的表格。每当我们输入员工薪水需要检查那个特定月份的退出时,提交表格时有一个日期字段来选择需要在哪个日期给出薪水。从表单中我们可以得到用户 ID 和月份。它的代码模型查询是什么

表名salary,数据库日期字段类型为date

请检查我的模型查询代码

public function ($userid, $month)
{
$this->db->where('salary_employee_id',$userid);
$this->db->where('salary_date',$month);
$query=$this->db->get('salary');
$query->row_array();

if(empty($query))
{
return true;
}
else{
return false;
}

}

最佳答案

由于数据库中的 salary_date 列是月份类型,因此该列中的数据将按如下方式存储:

2019-01-12
2019-02-01
2019-03-13

我假设日可以是一个月中的任何一天,不一定是每个月的第一天。所以你的 Mysql 查询应该对 salary_date 使用 LIKE 并且应该是这样的

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;
}
}

请注意,这只会检查当年。如果你想检查前几年或任何特定年份,你需要传递年份参数作为此函数的另一个参数。

更新

感谢@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;
}
}

关于php - Codeigniter- 检查用户在一个月内是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57940922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com