我正在使用codeigniter。以下是我的代码
public function get_content(){
$this->db->select('*');
$this->db->from('content_table');
$this->db->where('status', "Active");
$this->db->group_by('MONTH(content_publish_date)');
$query = $this->db->get();
return $query->result();
}
我想按月提取行数&结果将在月份显示.. 但根据上面的查询我每个月只得到一行..我需要所有行按月显示结果..请帮助。
答案 0 :(得分:2)
您需要使用ORDER BY
代替GROUP BY
这样做:
public function get_content(){
$this->db->select('*');
$this->db->from('content_table');
$this->db->where('status', "Active");
$this->db->order_by('MONTH(content_publish_date)', 'DESC');
$query = $this->db->get();
return $query->result_array();
}
将此代码写入您的视图文件中:
$month = "";
foreach($paaed_arr AS $row){
$dbmonth = date('m', strtotime($row['content_publish_date']);
if($month != $dbmonth){
echo date('F Y', strtotime($row['content_publish_date']));
$month = $dbmonth;
}
// Put your code here to display records of this month ....
}
GROUP BY用于对相同数据进行分组,而ORDER BY用于数据排序
让我知道更多帮助!
答案 1 :(得分:2)
要实现这一点,你应该订购日期栏。试试这个......
public function get_content(){
$this->db->select('*');
$this->db->from('content_table');
$this->db->where('status'), "Active");
$this->db->order_by("MONTH(content_publish_date)", "asc");
$query = $this->db->get();
return $query->result();
}
答案 2 :(得分:1)
首先你的where子句在语句
中有额外的括号$this->db->where('status'), "Active");
像这样改变
$this->db->where('status', "Active");
其次通过代替group by来添加顺序,但是order by应该是日期
$this->db->order_by('DATE(content_publish_date)', 'DESC');
第三次以select as
获取当前记录的月份$this->db->select('*,MONTH(content_publish_date) as content_publish_month');
表示您的最终查询将是
$this->db->select('*,MONTH(content_publish_date) as content_publish_month');
$this->db->from('content_table');
$this->db->where('status', "Active");
$this->db->order_by('DATE(content_publish_date)', 'DESC');
$query = $this->db->get();
return $query->result_array();
然后在视图中你必须添加一个变量,它将检查月份是否与前一个记录的月相同,然后只显示记录,否则显示月份标题,例如:
$lastMonth = 0;
foreach($result as $oneRec)
{
if(($lastMonth == 0) || ($lastMonth != $oneRec['content_publish_month'])
{
//show header
echo date('F Y', strtotime($row['content_publish_date']));
//check if its first record or not
if($lastMonth != 0)
{
echo '</table>';
}
//then add table start tag
echo = '<table><tr>
<th>Date</th>
<th>Title</th>
<th>Publication</th>
</tr>';
}
//show record here
echo = '<tr>
<td>'.$oneRec['content_publish_date'].'</td>
<td>'.$oneRec['title'].'</td>
<td>'.$oneRec['publication'].'</td>
</tr>';
//then set current record's month as last month as
$lastMonth = $oneRec['content_publish_month'];
}
echo '</table>';