存档php sql date()

时间:2013-09-16 11:23:14

标签: php mysql sql date

我已经开始了一些我不知道如何完成的事情。我建了一个名为'博客'的桌子。在博客表中有一列date。我使用date()函数来检索此列: “1360225336”。

我希望Archives按年,然后按月:

-2013

9.September 。 。 。 3.March 2.February 1.January

-2012

12.December 。 。 。 3.March 2.February 1.January

  <?php


        $query_o = mysql_query("SELECT * FROM `blog`")or die(mysql_error());

        while($row_o = mysql_fetch_assoc($query_o)){

        $new_date_y = date("Y", $row_o[date]);
        $new_date_m = date("n", $row_o[date]);


    $query_h = mysql_query("SELECT * FROM `blog` where date = $new_date_y ")or die(mysql_error());

    while($row_h = mysql_fetch_assoc($query_h)){

    $new_date_m1 = date("n", $row_o[date]);

echo'<ul>$new_date_y</ul>';
echo'<li>$new_date_m1</il>';
}



        }
    ?>

4 个答案:

答案 0 :(得分:1)

试试这个

$result = mysql_query("select distinct YEAR(date) as year from blog ") or die(mysql_error());

$years = array();

while($row = mysql_fetch_assoc($result))
      $years[] = $row['year'];

$one_year_posts = array();

foreach($years as $year){
    echo $year."<br/>";
    //echo "select * from blog where YEAR(date) = '$year'";
     $result1 = mysql_query("select * from blog where YEAR(date) = '$year'") or die(mysql_error());

     while($row1 = mysql_fetch_assoc($result1))
      $one_year_posts[] = $row1;

     foreach($one_year_posts as $post){
     //echo $post['date']."<br>";
      $months.=  date('m F',strtotime($post['date'])).", ";

  }
  echo $months = rtrim($months," ,");
}

答案 1 :(得分:0)

尝试此查询:

SELECT * FROM `blog` GROUP BY YEAR(`Date`), MONTH(`Date`);

如果您还需要day,请在最后添加, DAY(`Date`)

答案 2 :(得分:0)

$result = mysql_query("select distinct FROM_UNIXTIME(date,'%Y') as year from blog ") or die(mysql_error());

$years = array();

while($row = mysql_fetch_assoc($result))
      $years[] = $row['year'];

$one_year_posts = array();

foreach($years as $year){
    echo "<br/>-".$year."<br/>";
     $result = mysql_query("select * from blog where FROM_UNIXTIME(date,'%Y') = '$year'") or die(mysql_error());

     while($row = mysql_fetch_assoc($result))
      $one_year_posts[] = $row;

     foreach($one_year_posts as $post){
        echo strftime('%d %B',$post['date']).", ";
  }
}

注意:使用mysqli_而不是mysql_函数。后者已被弃用,不再维护。

答案 3 :(得分:0)

在尝试了很多新事物后,我终于成功了

<?php


$result = mysql_query("select distinct FROM_UNIXTIME(date,'%Y') as year from blog ") or die(mysql_error());

$years = array();

while($row = mysql_fetch_assoc($result))
$years[] = $row['year'];

$one_year_posts = array();

foreach($years as $year){



$result1 = mysql_query("select distinct FROM_UNIXTIME(date,'%M') as m from blog where FROM_UNIXTIME(date,'%Y') = '$year'") or die(mysql_error());

$ms = array();

while($row1 = mysql_fetch_assoc($result1))
$ms[] = $row1['m'];

$one_year_posts = array();

foreach($ms as $m){

$date= $year;
$date.= " ";
$date.= $m;

echo <<<PRINT
     <li><a href='search.php?archie=$date'>$date</a></li>
PRINT;

}


}
?>