按日期排序的日期字段Mysql/PHP
问题描述:
我无法让我的年份正确回显。按日期排序的日期字段Mysql/PHP
例如:我有两篇新闻文章,一篇是2011年的版本,另一篇是2012年的版本。他们正在分裂成正确的“年份”div。但是,当谈到渲染今年,它的工作原理。但2011年和2012年相互叠加。像这样的东西。
5.1.12我的新闻文章
如果2011年份假设去
5.1.11我的新闻文章
这是我的代码。
<?
$startYear = 2010;
$endYear = 2012;
for($y = $endYear; $y > $startYear -1; $y--) { ?>
<?
$news = query("SELECT * FROM news_entries
WHERE title > ''
AND published = 1
AND date >= '" . mktime(0,0,0,0,0,$y) . "'
AND date < '" . mktime(0,0,0,0,0,$y+1) . "'
ORDER BY date DESC");
?>
查询的其余部分。
<? if($news['total']>0) { ?>
<h3><? echo $y; ?></h3>
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<th class="first" width="125">Date</th>
<th>News Headline</th>
<th width="140"> </th>
</tr>
<? do { ?>
<tr>
<td><span><? echo date("F d, Y",$news['data']['date']); ?></span></td>
<td><a href="<? echo $baseURL . "news/" . $news['data']['id'] . "/" . htaccess_format($news['data']['name']); ?>" title="<? echo $news['data']['headline']; ?>"><? echo $news['data']['headline']; ?></a></td>
<td><a href="<? echo $baseURL . "news/" . $news['data']['id'] . "/" . htaccess_format($news['data']['name']); ?>" title="Learn More" class="button">Learn More</a></td>
</tr>
<? } while($news['data'] = mysql_fetch_assoc($news['object'])); ?>
<? }} ?>
<tr>
<td colspan="2" class="last"></td>
<td class="last"> <a href="javascript:;" title="Back to Top" class="top">Back to Top</a></td>
</tr>
</table>
答
我同意加藤的评论。通常,您可以获得所有结果并遍历它们,在数据更改时打印新的标题。
下面是这种类型的事情通常处理(伪):
$sql = "SELECT * FROM news_enteries ORDER BY date DESC";
// Prepare statement
$stmt = $pdo->prepare($sql);
// Bind variables
...
// Execute query
$stmt->execute() or die();
$year_header = "";
while ($row = $stmt->fetch()) {
$year = date("Y", strtotime($row['date']));
// Do we need a new year header?
if ($year_header <> $year) {
$year_header = $year;
// Print year header
echo $year_header;
}
// Process rest of the row
...
}
我加入到我原来的问题。 – LadyGuru 2012-02-16 16:41:24
您是否也将日期作为01/01/YYYY放入数据库?他们从来没有月/日信息?上面的操作实际上排除了01/01/2012之后的所有日期吗? (即实际上不包括2012?) – Kato 2012-02-16 16:53:17
@Kato他们正在做一个日期范围,在查询中每次一年。 – 2012-02-16 16:55:28