php - 在每个id php的单独行上显示一个id的所有记录
问题描述
我有这个表是由一些内部连接产生的
id_outfit | name | article
----------------------------------------
56 | one | shoe.png
56 | one | dress.png
56 | one | bag.png
54 | two | shoe1.png
54 | two | dress2.png
“文章”列包含图像。
我尝试在我的应用程序中显示来自 id_outfit 的所有文章,但我不知道该怎么做。
例如,我尝试在一行上显示所有 id 为 56 的文章,在下一行显示所有 id 为 54 的文章,依此类推。
我尝试使用 GROUP BY 执行此操作,但对于每个 id,它仅显示第一张图片(文章)。
任何建议对我都非常有帮助,谢谢!
解决方案
这是一种使用 PDO 语法的方法:
<?php
try{
$db = new PDO("mysql:host=localhost;dbname=yourdb", $user, $pass);
}
catch (Exception $e){
//Handle your connection errors
}
//Request the things you need
$req = $db->query("SELECT id_outfit, article FROM your_table ORDER BY id_outfit DESC");
$tempId = null;
//start to loop through your data
while ($data = $req->fetch()){
//if the outfit id is different than the last time we went through the loop:
if($data["id_outfit"] !== $tempId){
//close the previous row unless this is the first time through the loop
echo $tempId === null ? "" : "</div>";
//start a new row
echo "<div class='row'>";
}
//now we display the image
echo "<img src='" . $data["article"] . "' alt='youralt' >";
//store the id we had for the next loop to check
$tempId = $data["id_outfit"];
}
//close the last row
echo "</div>";
?>
这将为您的数据库中的每个不同 ID 输出一个div
类“行”,包含与该 ID 对应的所有图像。
然后,您可以使用 css 为这些 div 设置样式以将其显示为一行,很可能使用 flexbox:
.row{
display: flex;
}
(你需要更多的 CSS 才能让它变得非常明显。)
推荐阅读
- reactjs - 使用 docker 将 React 应用程序部署到谷歌云的文件结构
- python - Python子类函数将子类的实例更改为父类的实例
- .htaccess - Wordpress 302 通过 htaccess 临时重定向
- python - 是否可以选择随机运算符?
- java - MacOS 上的 Java NNS 错误,找不到库
- docker - 自定义 WSL 配置文件破坏了 docker 桌面
- javascript - 提交ajax表单
- c# - 如何在 ASP .NET MVC 中将 @title.visible 更改为 false
- c++ - 如何确定一个 URL 是否指向服务器本身?
- java - 通过将更大的数组切成块来创建子数组数组(Java)