Php - 按天记录的组记录

时间:2013-11-13 10:30:49

标签: php mysql datetime group-by

我有一张桌子:

  CREATE TABLE IF NOT EXISTS "visits" ( 
  "id" int(10) unsigned NOT NULL AUTO_INCREMENT,
  "start" datetime NOT NULL,
  "finish" datetime NOT NULL,
  "name" varchar(50) NOT NULL,
  PRIMARY KEY ("id")
)

我想显示接下来2天的访问次数,如下面的代码所示:

<div id="day>Today</div>
<a href="#">VISIT NAME</a>
<a href="#">VISIT NAME</a>
<a href="#">VISIT NAME</a>
<div id="day>Tomorrow</div>
<a href="#">VISIT NAME</a>
<a href="#">VISIT NAME</a>
<div id="day>15-11-2013</div>
<a href="#">VISIT NAME</a>

此刻我只有这个 我正在寻找PHP代码:)此时我只有:

$link=mysql_query('select count(*), DATE_FORMAT(start,"%Y-%m-%d") as start FROM visits GROUP BY start');
            while($row=mysql_fetch_array($link))
            {
            echo'<div id="day">'.$row['start'].' '.$row['count(*)'].'</div>';
            }

但仅显示

<div id="day>Today 3</div>
<div id="day>Tomorrow 2</div> 
<div id="day>15-11-2013 1</div>

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

试试这个。

$sql = "
    SELECT *, DATE(`start`) AS group_name
    FROM `visits`
    WHERE DATE(`start`) BETWEEN CURDATE() AND CURDATE() + INTERVAL 2 DAY
    ORDER BY `start` ASC
";
$result = mysql_query($sql) or die(mysql_error());
$group = null;
while ($row = mysql_fetch_assoc($result)) {
    if (is_null($group) || $group != $row['group_name']) {
        $group = $row['group_name'];
        echo '<div id="day">' . $row['group_name'] . '</div>';
    }
    echo '<a href="#">' . $row['name'] . '</a>';
}