简体   繁体   中英

Selecting date by month and year from database

I'm making a calendar with events in Codeigniter, so I want do build a list of this events sorted by month and year.

In database, I have the list of events and I want to retrieve then by the field date, that uses the DATE datatype.

    if($year != null and $month != null)
    {
        $this->db->where('date', '?');
    }
    $events = $this->db->get('agenda')->result();

Basically i have a yyyy-mm to compare with a yyyy-mm-dd.

Thank you and sorry for my English.

Assuming that $this->db->where() makes a AND field = value try this.

$this->db->where("DATE_FORMAT(date,'%d')", $month);
$this->db->where("DATE_FORMAT(date,'%Y')", $year );

The DATE_FORMAT() function is a MYSQL function for manipulating/formating dates so this should equate to

WHERE
     DATE_FORMAT(date,'%d') = '12'
 AND DATE_FORMAT(date,'%Y') = '2014'

Or you could use

$this->db->where('MONTH(date)', $month);
$this->db->where('YEAR(date)', $year );

In mysql your query should be like this

SELECT * FROM table_name WHERE data_field_name >='2000-10-1'  //Y-m-d

SELECT * FROM table_name WHERE data_field_name >='2000-10-1' AND data_field_name <='2014-10-1'

SELECT * FROM table_name WHERE data_field_name >='2000-10-1'

SELECT * FROM table_name WHERE data_field_name BETWEEN '2000-10-1' AND '2014-10-1'

You can do this also

SELECT * FROM table_name WHERE YEAR( data_field_name ) >= '2010' AND MONTH( data_field_name ) >='10' AND DAY( data_field_name ) >= '1'

etc....

for you use case I would do something like this

SELECT
    *, MONTH( date_field) as month
FROM
    table_name
WHERE
    something = '1'
ORDER BY 
    month

The best way to do this is as follows:

$monthstring = sprintf('%d-%d-01', $year, $month); /* make yyyy-mm-01 string */
$this->db->where ( "date >= '$monthstring'");
$this->db->where ( "date < '$monthstring' + INTERVAL 1 MONTH");

This is a good way to do this because it allows an index to be used to search the date column if one happens to be available.

It expands to this sort of MySQL where clause

 WHERE date >= '2014-07-01' AND date < '2014-07-01' + INTERVAL 1 MONTH

That's exactly what you need for an index range scan.

That query should solve your problem!

SELECT * FROM table_name WHERE data_field_name >='01/10/2000'

or

SELECT * FROM table_name WHERE data_field_name between '01/01/2009' and '01/01/2010'; //FOR YEAR

or

SELECT * FROM table_name WHERE data_field_name between '01/01/2009' and '01/02/2009'; //FOR MONTH

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM