如何从PHP中的phpmyadmin一起回显所有相同id的行

时间:2017-06-29 03:30:54

标签: php mysql phpmyadmin

我的代码:

  $stmt = $conn->prepare("SELECT tmdb_movies.movie_title, images.image_url
    FROM tmdb_movies
    JOIN images ON images.images_tmdb_id=tmdb_movies.tmdb_id
    GROUP BY tmdb_movies.movie_title,images.image_url");

 // Then fire it up
 $stmt->execute();
 // Pick up the result as an array
 $result = $stmt->fetchAll();

// Now you run through this array in many ways, for example
 for($x=0, $n=count($result); $x < $n; $x++){

     echo'
  '.$result[$x]["movie_title"].' - <img src="'.$result[$x]["image_url"].'"/>
  ';

}

示例:此代码如何使用ECHO数据

// SOME Stuff Here
The Dark Knight: - <img src="sdfsdfds.jpg"/>
// MORE STUFF HERE
// SOME Stuff Here
The Dark Knight: - <img src="zxfdy.jpg"/>
// MORE STUFF HERE

// SOME Stuff Here
Logan - <img src="rhfrg.jpg"/>
// MORE STUFF HERE
// SOME Stuff Here
Logan - <img src="sdfsqw.jpg"/>
// MORE STUFF HERE

我希望如何回应数据

// Some Stuff Here
The Dark Knight -   <img src="sdfsdfds.jpg"/> <img src="zxfdy.jpg"/>
// More Stuff Here

 // SOME Stuff Here
Logan - <img src="rhfrg.jpg"/> <img src="sdfsqw.jpg"/>
// MORE STUFF HERE

我希望你理解。

为什么ECHO数据是这样的?

因为我正在使用一对多关系表。我的图片表是这样的:

tmdb_id        images
1             sfdsfds.jpg
1             zcxz.jpg
2             fsfsdfs.jpg
3             dsfsdfs.jpg
3             dsfsfs.jpg
3            dfdsfdsw.jpg

tmdb_movies和images表都通过tmdb_id

连接

2 个答案:

答案 0 :(得分:1)

使用一个或多个图像显示电影的备用方式。这按标题分组,并使用GROUP_CONCAT为每个标题创建图像列表。

$qstr = "";
$qstr .= "SELECT tmdb_movies.movie_title, GROUP_CONCAT(images.image_url) as `images`\n";
$qstr .= "FROM tmdb_movies\n";
$qstr .= "  JOIN images ON images.images_tmdb_id=tmdb_movies.tmdb_id\n";
$qstr .= "GROUP BY tmdb_movies.movie_title\n";
$qstr .= "LIMIT 10;";
$stmt = $conn->prepare($qstr);

// Then fire it up
$stmt->execute();
// Pick up the result as an array
$result = $stmt->fetchAll();

// Now you run through the results, one row per movie title.
foreach($result as $x => $row) {
    echo "\n".$row["movie_title"] . " - ";
    //  Images will be comma separated if multiple images.
    $img_list = explode(',',$row['images'];
    foreach($img_list as $c => $img) {
        echo " <img src='".$img."'/>";
    }
}

答案 1 :(得分:0)

您可以进行中断排序,查找重复的电影标题,仅在标题发生变化时发出标题。

$qstr = "";
$qstr .= "SELECT tmdb_movies.movie_title, images.image_url\n";
$qstr .= "  FROM tmdb_movies\n";
$qstr .= "  JOIN images ON images.images_tmdb_id=tmdb_movies.tmdb_id\n";
$qstr .= "  GROUP BY tmdb_movies.movie_title,images.image_url";
$stmt = $conn->prepare($qstr);

// Then fire it up
$stmt->execute();
// Pick up the result as an array
$result = $stmt->fetchAll();

// Now you run through this array in many ways, for example
$lastTitle = "";
foreach($result as $x => $row) {
    if($lastTitle != $row["movie_title"]) {
        echo "\n".$row["movie_title"] . " - ";
        $lastTitle = $row["movie_title"];
    } else {
    }
    echo " <img src='".$row["image_url"]."'/>";
}