我编写了代码来从我的数据库中选择图像并显示它们,按月分组。我希望每个'月份的照片'都在自己的“容器”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月的FEB应该与2012年1月不同。
答案 0 :(得分: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循环后的最后一个divecho "</div>";
答案 1 :(得分: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/>";
}
}
?>
答案 2 :(得分: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/>";
}
}
&GT;
答案 3 :(得分: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
}
}
?>