0

我正在创建一个帖子存档,我想在以年/月格式创建文章时创建存档链接。

数据库中创建的日期以YYYY-MM-DD格式存储,到目前为止已经写了。

$archive =
  mysql_query("SELECT DISTINCT DateCreated FROM blog ORDER by DateCreated")
  or die("Could not execute query");

while($row = mysql_fetch_array($archive) ){ 
  $Date = explode("-", $row["DateCreated"]);
  $Year = $Date[0];
  $Month = $Date[1];

  // Months of the year.
  $MonthName = array(
    "01" => "JAN",
    "02" => "FEB", 
    "03" => "MAR",
    "04" => "APR",
    "05" => "MAY",
    "06" => "JUN",
    "07" => "JUL",
    "08" => "AUG",
    "09" => "SEP",
    "10" => "OCT",
    "11" => "NOV",
    "12" => "DEC");    

 $archiveData .=
   "<a href='archive.php?".$Year."-".$Month.
   "'>".$MonthName[$Month]."-".$Year."</a><br />"; 
}

如果我将这些日期存储在我的数据库中

2012-04-07, 
2012-05-02, 
2012-05-13, 
2012-02-22, 

然后上面的代码生成链接为

FEB-2012, 
APR-2012, 
MAY-2012, 
MAY-2012, 

它显示了已经添加的月份,我需要做的是限制它只显示一次。

我想我需要更改查询但不确定如何获得我需要任何帮助的结果将不胜感激。

4

4 回答 4

3
SELECT DISTINCT
  YEAR(DateCreated) AS yyyy,
  MONTH(DateCreated) AS mm
FROM blog 
ORDER BY DateCreated

并相应地

$Year = $row["yyyy"];
$Month  = $row["mm"];
于 2012-05-12T19:39:50.907 回答
1

你会尝试选择

DATE_FORMAT(DateCreated , '%m/%Y')

而不是“创建日期”?不确定结果,但据我所知,这应该可以解决您的问题。

问候

于 2012-05-12T19:40:40.083 回答
1

我认为这个查询对你来说是完美的——它选择前 3 个月的字母和时间戳的年份。

SELECT 
   substr(MONTHNAME(DateCreated), 1, 3) as month, 
   YEAR(DateCreated) as year
FROM blog 
ORDER by DateCreated DESC

编辑: 经过几次测试,我为您做了完美的查询-它以JAN-2012格式返回日期,因此无需在 PHP 中格式化日期。这里是:

SELECT 
   CONCAT( UPPER(substr(monthname(DateCreated), 1 ,3)), '-', YEAR(DateCreated)) as date
FROM blog 
ORDER by DateCreated DESC
于 2012-05-12T19:47:05.120 回答
0

我的最终结果是这样的。

$archive = mysql_query("SELECT DISTINCT YEAR(DateCreated) AS YYYY, MONTH(DateCreated) AS MM FROM blog ORDER BY DateCreated") or die("Could not execute query");

                while($row = mysql_fetch_array($archive) ){

                $Year               = $row["YYYY"];
                $Month              = sprintf("%02s",$row["MM"]);

                // Months of the year.
                $MonthName = array(
                                    "01" => "JAN",
                                    "02" => "FEB", 
                                    "03" => "MAR",
                                    "04" => "APR",
                                    "05" => "MAY",
                                    "06" => "JUN",
                                    "07" => "JUL",
                                    "08" => "AUG",
                                    "09" => "SEP",
                                    "10" => "OCT",
                                    "11" => "NOV",
                                    "12" => "DEC"
                                );    

                    $archiveData .=   "<a href='archive.php?".$Year."-".$Month."'>".$MonthName[$Month]."-".$Year."</a><br />"; 
                } 
于 2012-05-12T19:56:40.617 回答