tags:

views:

98

answers:

2

I am relatively new to Cake PHP framework and was trying few things in it. I have made a blog databse. I was trying to view an array of number of posts made in a particular year using the debug() function. I wrote the following function in the post model.

function findByYear($year = null){
     $date = $year.'-01-01 00:00:00';
     $end_date = $year.'-12-31 23:59:59';
     return $this->find('all',array('conditions'=>array('DATE(Post.date)'=>'>'.$date,'DATE(Post.date)'=>'<'.$end_date)));

    }

Then I included a read function in the posts_controller.

function read($year=null) {
      if (!$year) {
      $this->Session->setFlash('Please supply a year');
         $this->redirect(array('action'=>'index'));
        }
     $this->set('posts',$this->Post->findByYear($year));
    }

Finally, a created a read view file(read.ctp) and included the debug function in that

<?php debug($posts) ?>

Now, the problem is that I am getting an empty array when I launch the action in the URL: http://localhost/posts/read/2009 I already have 3 posts but I am not getting any of them in the array. What am I missing?

+1  A: 

I think the issue is the location of the "<" and ">" operators, because they have to be on the "key" side, and not on the "value" side. Change

'DATE(Post.date)' => '>'.$date

to

'DATE(Post.date) >' => $date

The same applies for the other condition.

dhofstet
A: 

The conditions array can be of mixed types (which is to say that it can contain strings as well as arrays). It might be easier to express the date-based criteria as strings, since you're working with a range instead of an exact match on the date. For example:

$conditions   = array();
$conditions[] = array('Post.id'=>$myId);
$conditions[] = 'DATE(Post.date) > '.$date;

$posts        = $this->find('all',array('conditions'=>$conditions));

(An ancillary benefit being that this is much easier for mere mortals to parse.)

Another point - you should consider using the mktime() function to build your date strings instead of simply concatenating the parameter to the front of the string and hoping for the best. This would serve the dual purpose of providing some rudimentary validation of the $year parameter as well as reducing the likelihood of getting unexpected results. For example:

$date     = mktime(0,0,0,1,1,$year); //$year.'-01-01 00:00:00';
$end_date = mktime(23,59,59,12,31,$year); //$year.'-12-31 23:59:59';

That will set both of your date values in the unix timestamp format, which is what you want anyway so it's a win from almost every angle.

Good luck!

inkedmn