我正在构建一个包含多个“单行文字”的网站。这些是使用简单的 PHP5 表单添加的,存储在 MySQL 5 数据库中。每行都有一个“id”(自动增量)、“标题”、“描述”、“状态”(1 或 0)和“日期添加”(MySQL 日期时间)。
我想按月和年分组显示它们,如下所示:
<dl>
<dt>August 2009</dt>
<dd><strong>title 1</strong> - description 1</dd>
<dd><strong>title 2</strong> - description 2</dd>
<dd><strong>title 3</strong> - description 3</dd>
etc...
</dl>
<dl>
<dt>July 2009</dt>
<dd><strong>title 1</strong> - description 1</dd>
<dd><strong>title 2</strong> - description 2</dd>
<dd><strong>title 3</strong> - description 3</dd>
etc...
</dl>
我发现了一个 MySQL 片段,表面上按月对行进行分组,但查询只返回几个结果,而不是完整的表:
SELECT `title`, `description`, `date_added`
FROM one_liners WHERE `status`=1 GROUP BY MONTH(date_added)
我将如何对它们进行分组,然后循环显示如上?
任何帮助将不胜感激。
谢谢!
最佳答案
您不想为此使用 GROUP BY
子句。尽管它“听起来”像您想要的,但它具有完全不同的含义。
运行普通查询:
SELECT `title`, `description`, `date_added` FROM one_liners
WHERE `status`= 1 ORDER BY `date_added`
然后循环结果,执行如下操作:
$query = 'SELECT `title`, `description`, `date_added` FROM one_liners WHERE `status`= 1 ORDER BY `date_added`';
$res = mysql_query( $query );
$month = null;
$year = null;
echo '<dl>';
while($row = mysql_fetch_assoc( $res ){
$r_month = strtotime( $row['date_added'] );
if($month != date('m', $r_month) || $year != date('Y', $r_month)){
echo '<dt>' . date('F Y', $r_month) . '</dt>';
$month = date('m', $r_month);
$year = date('Y', $r_month);
}
echo '<dd><strong>' . htmlentities( $row['title'] ) . '</strong> —' . htmlentities( $row['description'] ) . '</dd>';
}
echo '</dl>';
我专门选择仅使用一个 dl
,因为 dl
应该容纳许多 dd
和 dt
元素,而不仅仅是每个列表一对。如果您不同意,请随意根据需要调整我的代码:)
关于php - 使用 PHP 按周分组和显示 MySQL 条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2035938/