将varchar转换为where子句中的日期

时间:2014-04-15 09:30:04

标签: mysql sql codeigniter

function details_klanten($idKlant,$start,$eind){
    $this->db->select(' Project.idProject,
                        Project.Titel, 
                        Project.idProjecttype, 
                        Project.Begindatum, 
                        Project.Deadline, 
                        Project.idKlant,
                        Projecttypes.idProjecttypes,
                        Projecttypes.Type, 
                        Werknemer.idWerknemer,
                        Werknemer.Voornaam,
                        Statusproject.idStatusProject,
                        Statusproject.Soort,
                        Klant.Naam');
    $this->db->order_by('Titel', 'asc');
    $this->db->from('Project');
    $this->db->join('Klant', 'Klant.idKlant = Project.idKlant');
    $this->db->join('Projecttypes', 'Projecttypes.idProjecttypes = Project.idProjecttype');
    $this->db->join('Werknemer', 'Werknemer.idWerknemer = Project.idWerknemer');
    $this->db->join('Statusproject', 'Statusproject.idStatusProject = Project.idStatusProject');
                if ($idKlant > 0){
    $this->db->where('Klant.idKlant',$idKlant);
    $this->db->where('Project.Begindatum >',$start);
    $this->db->where('Project.Deadline <',$eind);
    }
    $query = $this->db->get();

    if($query->num_rows()>0){
        return $query->result();
    }
    else{
        return false;
    }
}

project.BegindatumProject.Deadlinevarchar(10)。因此,它会查看前两个数字而不是完整日期。例如:

$start = '01-04-2014';
'Project.Begindatum' = (Varchar)'02-03-2014'.

然后会显示因为 它仅适用于'01'(-04-2014) and the '02'(-03-2014)

1 个答案:

答案 0 :(得分:1)

使用mysql的 STR_TO_DATE() 功能,并将where()中的第三个参数传递为FALSE

$this->db->where("STR_TO_DATE(Project.Begindatum,'%d-%m-%Y') >",$start,FALSE);
$this->db->where("STR_TO_DATE(Project.Deadline,'%d-%m-%Y') <",$eind,FALSE);

最好更改要以标准格式存储的列类型使用date类型在数据库中存储日期,使用格式为STR_TO_DATE的{​​{1}},然后存储在表中的值应该有%d-%m-%Y格式,否则它不会工作,应该与%d-%m-%Y进行比较,否则你需要另一个函数,即DATE_FORMAT来格式化$start = '2014-04-01';

01-04-2014