使用mysql和php显示所有电影列表

时间:2018-06-05 18:19:38

标签: php mysql sql mysqli

我有一个数据库

-movie ( movie_id , title , year)
          1      , thor , 2017
          2      , deadpool,2018    
-genre ( genre_id , genre_name )
              1      , action
              2      , adventure
              3      , comedy    

-movie_genre ( movie_id , genre_id )
                     1     ,    1
                     1     ,    2
                     2     ,    2
                     2     ,    3

我的PHP代码是

<?php 
$info_query = mysql_query("
SELECT * 
  FROM movie
     , genre
     , movie_genre 
 WHERE movie.movie_id = movie_genre.movie_id 
   AND genre.genre_id = movie_genre.genre_id
")or die(mysql_error());
$info_count =mysql_num_rows($info_query);
while($info_row = mysql_fetch_array($info_query)){
    if ($info_count > 0){ ?>
        <?php echo $info_row['title'] ?>
        <?php echo $info_row['genre'] ?>
        <?php
    }  } 
?>

输出

thor action thor adventure

我想要

thor acton adventure
deadpool adventure comedy

2 个答案:

答案 0 :(得分:0)

<?php
$info_query = mysql_query("
    SELECT mv.movie_id, mv.title, gr.genre_name
    FROM movie_genre mg
    INNER JOIN movie mv ON mg.movie_id = mv.movie_id
    INNER JOIN genre gr ON mg.genre_id = gr.genre_id
")or die(mysql_error());

$info_count = mysql_num_rows($info_query);

if ($info_count > 0) {
    $movies = [];
    while ($info_row = mysql_fetch_array($info_query)) {

        if (!isset($movies[$info_row['movie_id']])) {
            $movies[$info_row['movie_id']] = ['title' => $info_row['title'], 'genres' => []];
        }

        $movies[$info_row['movie_id']]['genres'][] = $info_row['genre_name'];
    }

    foreach ($movies as $movie_id => $movie ) {
        echo $movie['title'] .' ';
        foreach ($movie['genres'] as $genre) {
            echo $genre . ' ';
        }
        echo "\n<br>";
    }
}

答案 1 :(得分:-2)

此查询应该有效:

SELECT title, 
GROUP_CONCAT(genre_name) AS genre
FROM movie_genre 
JOIN movie ON movie.movie_id = movie_genre.movie_id 
JOIN genre ON genre.genre_id = movie_genre.genre_id 
GROUP BY title

然后在php中,如果你希望你可以用空格替换逗号,如下所示;

<?php 
echo $info_row['title'];
echo str_replace(',',' ',$info_row['genre']);
?>