首页 > 解决方案 > 在每个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,它仅显示第一张图片(文章)。

任何建议对我都非常有帮助,谢谢!

标签: phphtmlcssmysql

解决方案


这是一种使用 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 才能让它变得非常明显。)


推荐阅读