Php 在while循环期间创建新div
我编写了代码,从数据库中选择图像并按月份分组显示它们。我希望每个“照片月”都在它自己的“容器”分区中。我不知道如何在while循环中执行此操作。我想我需要一种方法来判断下一行数据是否是一个新的月份,这将被迭代。有什么建议吗 我的代码:Php 在while循环期间创建新div,php,mysql,css,Php,Mysql,Css,我编写了代码,从数据库中选择图像并按月份分组显示它们。我希望每个“照片月”都在它自己的“容器”分区中。我不知道如何在while循环中执行此操作。我想我需要一种方法来判断下一行数据是否是一个新的月份,这将被迭代。有什么建议吗 我的代码: <?php if (isset($_COOKIE['user_id'])) { if (!isset($_GET['user_id'])) { $user_id= $_COOKIE['user_id']; } else { $user_id= $_GET[
<?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中。我会尝试以下方法来检查是否已打开新容器:
<?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/>";
}
}
?>
在创建月份标题的同一位置实现这一点非常容易
$first = true;
if ($date != $row['date']) {
if ($first) {
$first = false;
} else {
echo "<\div>";
}
echo "<div><p> ".$row['date']."</p><br/>";
$date = $row['date'];
}
$first=true;
如果($date!=$row['date'])){
如果($第一){
$first=false;
}否则{
回声“;
}
回显“”$row['date']。“
”;
$date=$row['date'];
}
然后,您必须通过调用以下命令来关闭while循环后的最后一个div:
echo "</div>";
echo”“;
试试这样的事情:
<?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
}
}
?>
您可以有超过12个月的时间,因为您可以显示几年的照片。
echo "</div>";
<?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
}
}
?>