Search code examples
codeignitersortingdateblogsarchive

How to show data from within a specific time period in codeigniter?


I am creating an archive view for my blog.

I have a url that looks the following:

www.mydomain.com/blog/archive/2012-May

How can I get all blog posts from the database that were created during May 2012???

I am using mysql datetime to store the date created. Format in DB: 2012-03-14 14:39:47

This is my code so far:

    function get_archive_posts(){

    $data = '';

//NEED TO GROUP AND GET BY DATE AND YEAR IN URL

        $this->db->order_by('date','desc');
        $query = $this->db->get('blog'); 
        foreach ($query->result() as $row) {
            $data[] = array(
                'id' => $row->id,
                'date' => $row->date,
                'title' => $row->title,
                'content' => $row->content,
                'category' => $row->category,
                'author' => $row->author
            );
        }
        return $data;
    }

How can I order by the month and year shown in the url and only show these posts???


Solution

  • To make monthly archive i think it will be good idea to store the month and year of the post in separate column of the table so we can easily fetch the data that fall within that month and year. I think with the current date format it will be not possible to check the month and year of the post so do one thing get the month and year from the post date and store them in table then compare the month and year with archive month and year. I think it will be far easy to do this in this way.
    Hopefully this will help you.