gpt4 book ai didi

php - 在 mysql 和 php 中按年份分类

转载 作者:行者123 更新时间:2023-11-29 00:29:05 28 4
gpt4 key购买 nike

我正在尝试用简单的 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 = '".$year."'");
while($album = mysql_fetch_object($query2)){
echo "<a href=\"".$album->url."\">".$albumName."</a><br>";
}
} ?>

如您所知,将两个 while 循环合二为一真的很糟糕,所以我想换一种方式。我想学习如何更好地做到这一点。问题是,我不知道它的名字,所以很难搜索这个主题。有没有人能给我一段代码、源代码或其他东西来让我上路?

非常感谢。

最佳答案

你可以做

<?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 - 在 mysql 和 php 中按年份分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17438728/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com