在mysql和php中按年份进行分类
我正试图用简单的PHP编写一个相册程序,但我想让它比以前更高级一点 通常我是这样写的:在mysql和php中按年份进行分类,php,mysql,Php,Mysql,我正试图用简单的PHP编写一个相册程序,但我想让它比以前更高级一点 通常我是这样写的: <?php $query = mysql_query("SELECT year FROM photo"); while($record = mysql_fetch_object($query)) { echo $record->year."<br>"; $query2 = mysql_query("SELECT albumName, url FROM photo WHERE year
<?php $query = mysql_query("SELECT year FROM photo");
while($record = mysql_fetch_object($query)) {
echo $record->year."<br>";
$query2 = mysql_query("SELECT albumName, url FROM photo WHERE year = '".$year."'");
while($album = mysql_fetch_object($query2)){
echo "<a href=\"".$album->url."\">".$albumName."</a><br>";
}
} ?>
如果您这样做:
<?php $query = mysql_query("SELECT albumName, url, year FROM photo");
while($record = mysql_fetch_object($query)) {
echo $record->year."<br>";
echo "<a href=\"".$record->url."\">".$albumName."</a><br>";
}
?>
怎么了?
现在,如果每年有许多相册,那么您的代码可能会多次生成相册 如果您这样做:
<?php $query = mysql_query("SELECT albumName, url, year FROM photo");
while($record = mysql_fetch_object($query)) {
echo $record->year."<br>";
echo "<a href=\"".$record->url."\">".$albumName."</a><br>";
}
?>
怎么了?
现在,如果每年有许多相册,那么您的代码可能会多次生成相册 你可以这样做
<?php
$year = ''; // create a generic variable that will hold the album year
$query = mysql_query("SELECT albumName, url, year FROM photo ORDER BY year"); // Sort by year
while($album = mysql_fetch_object($query)) {
if($album->year != $year){ // check if $album->year is the same as the $year value
echo $album->year."<br>"; // if not the same echo the year
}
$year = $album->year; // set the $year value to the $album->year
echo "<a href=\"".$album->url."\">".$album->albumName."</a><br>";
}
?>
你可以这样做
<?php
$year = ''; // create a generic variable that will hold the album year
$query = mysql_query("SELECT albumName, url, year FROM photo ORDER BY year"); // Sort by year
while($album = mysql_fetch_object($query)) {
if($album->year != $year){ // check if $album->year is the same as the $year value
echo $album->year."<br>"; // if not the same echo the year
}
$year = $album->year; // set the $year value to the $album->year
echo "<a href=\"".$album->url."\">".$album->albumName."</a><br>";
}
?>
这正是我想要的!非常感谢你!这正是我要找的!非常感谢你!如果我这样做的话,那就意味着它会在每一张专辑的名字之前显示专辑的年份。问题是:目前只有两年的时间,每年发行超过10张专辑。肖恩的回答很管用,但谢谢你的帮助!如果我这样做的话,那就意味着它会在每一张专辑的名字之前显示专辑的年份。问题是:目前只有两年的时间,每年发行超过10张专辑。肖恩的回答很管用,但谢谢你的帮助!