This is my current code, it works fine with one problem.
$stmt = $conn->prepare("SELECT * FROM tmdb_movies JOIN genres ON genres.genres_tmdb_id=tmdb_movies.tmdb_id
");
// 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
foreach ($result as $row) {
print "".$row["movie_title"]." ".$row["genres_name"] ." ".$row["cast_name"] ."<br/>";
}
The thing is, I am trying to echo Movie Name and it's Genres.
What I want to echo:
The Dark Knight - Action, Crime, Drama
What the code echo:
The Dark Knight - Action
The Dark Knight - Crime
The Dark Knight - Drama
Screenshot of main movie table http://prntscr.com/fokwip
and Screenshot of genres movie table http://prntscr.com/fokwoy
To echo what you want you can change your sql query :
$stmt = $conn->prepare("SELECT *, GROUP_CONCAT(genres.genres_name SEPARATOR ', ') AS genre_concat FROM tmdb_movies JOIN genres ON genres.genres_tmdb_id=tmdb_movies.tmdb_id GROUP BY tmdb_movies.movie_title");
// sql strict group by
$stmt = $conn->prepare("SELECT tmdb_movies.movie_title, tmdb_movies.cast_name, GROUP_CONCAT(DISTINCT genres.genres_name SEPARATOR ', ') AS genre_concat FROM tmdb_movies JOIN genres ON genres.genres_tmdb_id=tmdb_movies.tmdb_id GROUP BY tmdb_movies.movie_title, tmdb_movies.cast_name ORDER BY tmdb_movies.movie_title");
$stmt->execute();
$result = $stmt->fetchAll();
foreach ($result as $row) {
print "".$row["movie_title"]." ".$row["genre_concat"] ." ".$row["cast_name"] ."<br/>";}
GROUP_CONCAT allows to concat all the different genre for each unique movie title.
More Documentation :
GROUP BY : https://www.w3schools.com/sql/sql_groupby.asp
GROUP_CONCAT : https://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat
You can use group by
and group_cancat
like that:
SELECT
tmdb_movies.*, group_concat(genres.genres_name) as genres_names
FROM
tmdb_movies
JOIN
genres
ON
genres.genres_tmdb_id=tmdb_movies.tmdb_id
GROUP BY
tmdb_movies.movie_id
And then prints it:
foreach ($result as $row) {
echo "{$row['movie_title']} - {$row['genres_names']}<br/>";
}
Alternative SQL(it seems better than above sql):
SELECT
tmdb_movies.*, temp.genres_names
FROM
tmdb_movies
JOIN
(
SELECT
genres_tmdb_id, group_concat(genres_name) as genres_names
FROM
genres
GROUP BY
genres_tmdb_id
) temp
ON
temp.genres_tmdb_id = tmdb_movies.tmdb_id
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.