How can PHP code be optimized to display film information in a single row with all genres listed for each film?
To optimize PHP code to display film information in a single row with all genres listed for each film, we can use SQL queries to fetch the film data and genres, then use PHP to format the output in a single row for each film with all genres listed.
<?php
// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "films_database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch film data and genres
$sql = "SELECT films.title, GROUP_CONCAT(genres.genre) AS genres
FROM films
LEFT JOIN film_genres ON films.id = film_genres.film_id
LEFT JOIN genres ON film_genres.genre_id = genres.id
GROUP BY films.id";
$result = $conn->query($sql);
// Display film information in a single row with all genres listed
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "Film: " . $row["title"] . " | Genres: " . $row["genres"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Keywords
Related Questions
- In what situations might including header and footer files in PHP scripts lead to issues with session management and output buffering?
- In a PHP-SQL environment, where and how should options fields be integrated, and are functions or arrays necessary for this task?
- How important is it to reference the PHP documentation when trying to solve coding issues like string manipulation?