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();
?>