首页 > 解决方案 > 如何只显示一次评论,但在 PHP 中显示来自 mysql 的所有图像?

问题描述

我只想显示一次评论,例如(testsetest)与相关图像(通过连接两个表具有相同的imageid)。

示例(我想实现):评论:图片傻瓜:name1,name 2

错误输出的标题。

数据库结构

帖子:

| commentid |  comment  | iamgesid |
------------------------------------
|     1     |   fool    |   5557   |
|     2     |  fool2    |   5585   |
------------------------------------

多重图像:

| id |  image  | imagesid |
---------------------------
| 1  |  name1  |    5557  |
| 2  |  name2  |    5557  |
| 3  |  name3  |    5585  |
---------------------------

这是我当前的代码:

$sql = "SELECT image, posts.imagesid, multiple_image.imagesid, comment
        FROM multiple_image JOIN posts ON (multiple_image.imagesid=posts.imagesid)";
$result = $conn->query($sql);

if (!$result) {
    trigger_error('Invalid query: ' . $conn->error);
}

if ($result->num_rows > 0) {

    // output data of each row
    while($row = $result->fetch_assoc()) {

echo $row['comment'];
$imgs= "<div id='img_div'><img width='' src='upload/".$row['image']."' ></div>";
echo $imgs;
}
}

标签: phpmysqldatabasemysqli

解决方案


您将需要通过 commentid 控制中断结果和顺序

请查看更新后的代码。


$sql = "SELECT 
          image, 
          posts.imagesid, 
          multiple_image.imagesid, 
          comment
        FROM
           multiple_image 
        JOIN posts ON (multiple_image.imagesid=posts.imagesid)
        ORDER BY 
           commentid
";

$result = $conn->query($sql);

if (!$result) {
    trigger_error('Invalid query: ' . $conn->error);
}


if ($result->num_rows > 0) {

    // output data of each row
    $comment = '';
    while($row = $result->fetch_assoc()) {
      if($comment != $row['comment']){
         echo $row['comment'];
         $comment = $row['comment'];
      }

        $imgs= "<div id='img_div'><img width='' src='upload/".$row['image']."' ></div>";
        echo $imgs;
    }
}

推荐阅读