假设我在数据库中有一条记录,其日期时间为:2016-03-10 00:00:00,结束日期时间2016-03-10 06:00:00。现在,每次我在数据库中插入新记录时,我都要检查启动DateTime&结束日期时间使得持续时间不会与数据库中存在的先前记录重叠。 PHP CodeIgniter中是否存在任何内置函数来检查它?
现在我正在使用以下代码执行此操作,但它不起作用:
public function check_b_adds($data){
$sql='select * from listing_b_screen where (start_time >= ? AND end_time >= ?) OR (start_time <= ? AND end_time <= ?) OR (start_time <= ? AND end_time >= ?) OR (start_time = ? AND end_time = ?) OR (start_time >= ? AND end_time <= ?)';
$query=$this->db->query($sql, array($data['mystart_time'],$data['myend_time'],$data['mystart_time'],$data['myend_time'],$data['mystart_time'],$data['myend_time'],$data['mystart_time'],$data['myend_time'],$data['mystart_time'],$data['myend_time']));
$result = $query->result_array();
if ($result == NULL || $result == 0){
return false;
} else {
return True;
}
}
答案 0 :(得分:1)
$fromdaysDate="2016-07-13";//changed date
$todaysDate="2016-07-25";//changed date
$this->db->select('task_id,task_start_date, task_due_date');
$this->db->where('task_start_date <="'.date('Y-m-d', strtotime($fromdaysDate)).'"');
$this->db->where('task_due_date >="'.date('Y-m-d', strtotime($todaysDate)).'"');
$this->db->or_where('task_due_date BETWEEN "'. date('Y-m-d', strtotime($fromdaysDate)). '" and "'. date('Y-m-d', strtotime($todaysDate)).'"');
$alltask=$this->db->get('wba_task')->result_array();
echo $this->db->last_query();
答案 1 :(得分:0)
不知道你的db表是什么样的,但下面是一个例子:
public function check_b_adds($data){
//I suppose your start_time and end_time are stored as datetime type in db like 2016-03-01 07:30:00
$myStart_time = $data['mystart_time']; //for example, this is a string like 2016-03-01 07:30:00 in the format of %Y-%m-%d %H:%i:%s
$myEnd_time = $data['myEnd_time']; //for example, this is a string like 2016-03-01 09:30:00 in the format of %Y-%m-%d %H:%i:%s
$query = $this->db("
select *
from listing_b_screen
where id not in
(
select id
from listing_b_screen
where start_time > STR_TO_DATE('$myEnd_time', '%Y-%m-%d %H:%i:%s')
or end_time < STR_TO_DATE('$myStart_time', '%Y-%m-%d %H:%i:%s')
)
");
$result = $query->result_array();
if ($result == NULL || $result == 0){
return false; //not overlap
} else {
return true;
}
}
请注意您的逻辑错误。例如,db中的start_time和end_time是第3和第7,数组中的start_time和end_time是第1和第2。这不重叠。但你的逻辑start_time&gt; =? AND end_time&gt; =?认为它是重叠的。尝试在查询中使用“not in”