【问题标题】:Codeigniter 2.1 - Count data in DB for every monthCodeigniter 2.1 - 每月统计数据库中的数据
【发布时间】:2012-12-11 22:12:58
【问题描述】:

我有一个小的日历页面,您可以在其中单击特定月份并获取该月的所有文章。有几个月没有文章,我想避免用户点击那个月却发现它是空的部分。如何计算一年中每个月的所有文章以及查看部分中的最新数据?

文章的数据库是这样的:

articles
id_articles -> **number**
title -> **varchar**
text -> **text**
date_created -> timestamp (CURRENT_TIMESTAMP - MM/DD/YYYY HH:MM:SS ) 

HTML 代码:

<nav id="arcive" class="clearfix">
        <ul>
            <li>
                <a role=slide rel=2012 class="current" >2012</a>
                <ul rel=2012 class="month">
                    <li>
                        <a href="#">December</a>
                        <a href="#">November</a>
                        <a href="#">October</a>
                        <a href="#">September</a>
                        <a href="#">August</a>
                        <a href="#">July</a>
                        <a href="#">Jun</a>
                        <a href="#">May</a>
                        <a href="#">April</a>
                        <a href="#">March</a>
                        <a href="#">February</a>
                        <a href="#">January</a>
                    </li>
                </ul>
            </li>
    </ul>
    </nav>

【问题讨论】:

  • 可以发一下表结构吗? =o) 我们知道正在处理哪些类型的字段,因为这可能需要使用内置的 MySQL 函数来计算月份。还附带日历的 HTML 表单和与之相关的任何 PHP 代码。我们需要的不仅仅是一个表格列的列表才能做到这一点。
  • @cryptic 我添加了 HTML 代码。上面的表格结构就是文章的全部内容。
  • 表格列的字段类型有哪些?
  • @cryptic 添加了字段类型。

标签: php mysql codeigniter codeigniter-2


【解决方案1】:

动态创建菜单的 PHP 是这样的:

$year = '2012'; // set this to whatever the year to be queried is

$sql = 'SELECT GROUP_CONCAT(MONTH(`date_created`)) `date_created`  '
     . 'FROM `articles` '
     . 'WHERE YEAR(`date_created`) = ' . (int) $year; // typecast for security

// run query to return list of numeric months with articles
$query = $this->db->query($sql);  
$result = $query->row();
$months = explode(',', $result->date_created);

$articles_per_month = array_count_values($months); // get count of articles per each month    

for ($i = 1; $i <= 12; $i++) // Loop Through 12-months
{
    $month_name = date('F', mktime(0, 0, 0, $i)); // Get the name of the month from the numeric month

    echo (in_array($i, $months)) // Check to see if articles for month, if so create link otherwise SPAN
        ? "<a href='/calendar/month/$i'>$month_name (" . $articles_per_month[$i] . ")</a>\n" // print link with number of articles
        : "<span>$month_name</span>\n";
}

这将创建菜单,如果一个月没有文章,则会在 SPAN 标签中打印出月份名称,如果有文章,则会将月份打印为链接以及该月的文章数量。

【讨论】:

  • 解决头痛和流感的好方法 ;)
  • @MD.SahibBinMahboob 谢谢你,但是我对答案不满意并重新做了,现在好多了=o)
  • @cryptic 抱歉让您久等了,即使是新手程序员也需要睡觉:D。谢谢你的解决方案:)
  • @cryptic 一个简单的问题。有什么方法可以统计每月的文章数吗?
  • @cryptic 非常感谢:)。你是一个真正的救星。如果你来 Pirot,请打电话给我喝一杯 :)
猜你喜欢
  • 1970-01-01
  • 2017-04-28
  • 2018-02-13
  • 2018-04-03
  • 2023-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多