drruhc4944 2011-11-07 16:25
浏览 26
已采纳

选择今年的日期和按月分组

I'm working on an events page where users can create events and their followers can view the event on their events page.

What I would like to do is select all the events from the table where the event date is within this year (2011), so if the date is 2011-03-30 it will display in the March header, but if it's 2012-03-30 it wont display at all until next year.

So overall, I would like all events to display under headers, e.g. January, February, March.

My table structure is thus:

id                             int(11)
event_creator_user_id          int(11)
event_creator_user_username    varchar(255)
event_creator_user_first_name  varchar(255)
event_creator_user_last_name   varchar(255)
event_name                     varchar(255)
event_date                     date
event_time                     time
event_brief_location           varchar(255)
event_location_street          varchar(255)
event_location_town            varchar(255)
event_location_post_code       varchar(255)
event_description              text
event_create_date              datetime
type                           enum('a','b')
  • 写回答

3条回答 默认 最新

  • dpka7974 2011-11-07 16:39
    关注

    I think you are over complicating the problem. This can be solved by simply getting all the events in the current year using MySQLs DATE_FORMAT function and ordering the events by date.

    Then in PHP you can simply loop over them and when the month changes print out a heading. The code below should make this clearer.

    In PHP:

    $conn = mysql_connect("localhost", "mysql_user", "mysql_password");
    mysql_select_db("mydbname");
    
    $SQL = "
        SELECT *,
               UNIX_TIMESTAMP(`event_date`) AS event_date_timestamp
        FROM events
        WHERE DATE_FORMAT(event_date, '%Y') = 2011
          AND event_date > NOW()
        ORDER BY event_date ASC";
    
    $result = mysql_query($SQL);
    
    $current_month = '';
    while ($event = mysql_fetch_assoc($result)) {
        $month = date('m', $event['event_date_timestamp']);
        if($current_month != $month) {
            $current_month = $month;
            echo '<h1>' . $current_month . '</h1>';
        }
        echo '<p>' . $event['event_name'] . '</p>';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用