使用mysql和php只返回一次月份和日期

时间:2012-05-12 19:35:08

标签: php mysql arrays date

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

数据库中创建的日期以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 个答案:

答案 0 :(得分:3)

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

因此

$Year = $row["yyyy"];
$Month  = $row["mm"];

答案 1 :(得分:1)

你会尝试选择

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

而不是“DateCreated”?不确定结果,但据我记得,这应该可以解决你的问题。

此致

答案 2 :(得分: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

答案 3 :(得分: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 />"; 
                }