K
K
kslv12020-05-26 21:09:30
PHP
kslv1, 2020-05-26 21:09:30

Selecting elements from a table. How to do it right?

The task is to make a selection from the serial_genre table and display it on the site, in which two genres belong to one series. Quite a lot of attempts have been made to extract the correct values, but always displays "Detective", i.e. id=1. Below I will attach examples of how I did it, suddenly I miss some trifle.
5ecd5aae18b9e036958271.png
Here is the query in the database:

function get_genre_by_id($id)
{
  global $db;
  $genre = $db->query("SELECT serial.serial_name, genre.genre_name FROM serial INNER JOIN (genre INNER JOIN serial_genre ON genre.genre_id = serial_genre. genre_id) ON serial.serial_id= serial_genre.serial_id");
  foreach ($genre as $genre_name) {
    return $genre_name;
  }
}


The request is correct, I checked in phpmyadmin - it builds a table with the correct values, everything is ok.

An attempt to output a loop through while - makes infinity "Detective", everything freezes tightly.
An attempt to display through foreach displays 4 "Detective" and that's it. Maybe they are missing some condition, maybe there is an error somewhere else.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
AUser0, 2020-05-26
@AUser0

The simplest, most stupid, but working option:

SELECT serial.serial_name, genre.genre_name
FROM serial
LEFT JOIN serial_genre ON serial_genre.serial_id = serial.serial_id
LEFT JOIN genre ON genre.genre_id = serial_genre.genre_id

G
galaxy, 2020-05-26
@galaxy

First, use LEFT JOIN as written above (suddenly the series is not assigned a genre).
Secondly, with a simple join, there will be duplicate serials, i.e. multiple lines like

Сериал1    Детектив
Сериал1    Боевик

Either parse them in PHP, or GROUP_CONCAT will help in your simple case (there was a similar question )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question