2012-04-12 71 views
0

我想显示我的用户图片,按日期分组,如我的附加图片。我需要做什么?使用PHP订购MySQL数据

我到目前为止有:

$connect= //connection info; 
$query= "SELECT * FROM posts WHERE user_id= $user_id AND picture= IS NOT NULL ORDER BY date DESC"; 

$result= ($connect, $query); 

while ($row= mysqli_fetch_array($result)) { 
echo '<img src="'.$row['picture']. '"/>' . "<br/>"; 
}; 

而我的表结构:

| user_id | post_date | story | image | 
|-------------------------------------| 
| 14  | mar 2012 | BLOB | a.jpg | 
| 14  | apr 2012 | BLOB | b.jpg | 
| 14  | feb 2012 | BLOB | c.jpg | 
| 14  | mar 2012 | BLOB | d.jpg | 
|_____________________________________| 

但这个代码只显示全部用户收集图像。我如何分组他们?

Photos

+0

什么时间信息和格式化您的数据库条目有? – Claaker 2012-04-12 20:15:05

+0

多维数组。 $ userPictures ['date'] = data;然后将每个阵列呈现为一个组。 – Corbin 2012-04-12 20:15:38

+0

我们可以看到您的完整查询以及您所呼叫表中的所有关联字段吗?这将有助于改进SQL。 – 2012-04-12 20:14:22

回答

1

这个添加到查询的末尾(调整为特定的查询):

ORDER BY date ASC 

为了更好的细节,告诉我们您的查询,该表说明或样品表行。

0

添加ORDER BY日期DESC(好像你已经有了)到您的查询作为dotancohan年底提出,并随着时间的推移检查用你的for循环,例如

$date = "0"; 

while ($row= mysqli_fetch_array($result)) { 

    if (date('dmY', $date) != date('dmY', $row['date'])) { 
    echo "<p> NEW ROW, DATE: $row[date]</p>"; 
    $date = $row['date']; 
    } 

    echo '<img src="'.$row['picture']. '"/>' . "<br/>"; 
} 

的代码假定你在MySQL日期以时代格式(从1970年1月1日开始的整数)。似乎你只把月份和年份作为字符串,然后只使用$ date!= $ row ['date'] in if语句没有按日期转换函数。

0

在您的SQL查询,提取月份和年份从您的日期如下:

SELECT *, MONTH(date_field) AS month, YEAR(date_field) AS year FROM table 
ORDER BY date_field DESC 
在你的PHP视图

然后做这样的事情:

<div class="month-wrap"> 
    <? $i = 0; foreach ($data as $item){ ?> 

     <? if ($i > 0 && $last_month != $item['month'] && $last_year != $item['year']){ ?> 
      </div><div class="month-wrap"> 
      <?= $item['month'] ?>, <?= $item['year'] ?> 
     <? } ?> 

     <? if ($i == 0){ ?> 
      <?= $item['month'] ?>, <?= $item['year'] ?> 
     <? } ?> 

     <img src="<?= $item['image'] ?>" /> 

     <? 
      $last_month = $item['month']; 
      $last_year = $item['year']; 
     ?> 

    <? $i++; } ?> 
</div>