-1

我编写了代码以从数据库中选择图像并按月份分组显示它们。我希望每个“照片月”都放在自己的“容器”div中。我无法弄清楚如何在 WHILE LOOP 中执行此操作。我想我需要一种方法来判断将要迭代的下一行数据是否是新月份。有什么建议么?

我的代码:

<?php

if (isset($_COOKIE['user_id']))
{
if (!isset($_GET['user_id']))
{
$user_id= $_COOKIE['user_id'];
}
else
{
$user_id= $_GET['user_id'];
}

$connect= mysqli_connect("localhost", "root", "", "si");
$query= "SELECT * FROM posts WHERE user_id= $user_id ORDER BY date DESC";

$result= mysqli_query($connect, $query)
or die('error with query');
$date = "0";

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

if ($date != $row['date']) {
 echo "<p> ".$row['date']."</p><br/>";
 $date = $row['date'];
}

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

这是它的外观...

在此处输入图像描述

例如,2012 年 2 月的月份应该与 2012 年 1 月位于不同的容器 div 中。

4

4 回答 4

1

在您创建月份标题的同一位置实现这一点非常容易。

$first = true;
if ($date != $row['date']) {
    if ($first) {
        $first = false;
    } else {
        echo "<\div>";
    }
    echo "<div><p> ".$row['date']."</p><br/>";
    $date = $row['date'];
}

然后你必须通过调用关闭while循环后的最后一个div:

echo "</div>";
于 2012-04-15T17:03:01.277 回答
0

我会尝试这样的事情来检查是否打开了新容器:

<?php

if (isset($_COOKIE['user_id']))
{
if (!isset($_GET['user_id']))
{
$user_id= $_COOKIE['user_id'];
}
else
{
$user_id= $_GET['user_id'];
}

$connect= mysqli_connect("localhost", "root", "", "si");
$query= "SELECT * FROM posts WHERE user_id= $user_id ORDER BY date DESC";

$result= mysqli_query($connect, $query)
or die('error with query');
$date = "0";

$firstmonth = true; //used to tell if a div has been opened yet or not

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

if ($date != $row['date']) {
 if(!$firstmonth){ //close existing row first if needed
    echo "</div>";
    $firstmonth = false;
 }
 echo "<div class="month-container"><p> ".$row['date']."</p><br/>";
 $date = $row['date'];
}

echo '<img src="'.$row['picture']. '"/>' . "<br/>";
}
}
?>
于 2012-04-15T17:00:41.793 回答
0
<?php

if (isset($_COOKIE['user_id']))
{
if (!isset($_GET['user_id']))
{
$user_id= $_COOKIE['user_id'];
}
else
{
$user_id= $_GET['user_id'];
}

$connect= mysqli_connect("localhost", "root", "", "si");
$query= "SELECT * FROM posts WHERE user_id= $user_id ORDER BY date DESC";

$result= mysqli_query($connect, $query)
or die('error with query');

$date = "0";
$it= 0;

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

if ($date != $row['date']) {
if ($it < 1) {
echo "<div class='container'><p> ".$row['date']."</p><br/>";
 $date = $row['date'];
 $it ++;
    }
else {
 echo "</div><div class='container'><p> ".$row['date']."</p><br/>";
 $date = $row['date'];
 $it ++;
 }

}

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

?>

于 2012-04-15T17:01:59.323 回答
0

尝试这样的事情:

<?php
for($i =1; $i <= 12; $i++)
{
 $result = mysql_fetch_array(mysql_query("SELECT * FROM `posts` WHERE `user_id` = '" . $user_id . "' AND `month` = '" . $i . "'"));
 if(count($result))
    {
      // create the container and the images for the current month here
    }
}
?>
于 2012-04-15T17:09:08.610 回答