I needed some data from a database in mysql. However, the data were in different tables, so the most obvious solution was to filter using the relational tables, with their indexes. But I do not know much about mysql, I even tried to use the relational tables in phpmyadmin, but I did not know how to do it.
What to do? Obviously I would not sit idly in front of the pc, so I tried to create a solution with a script in PHP, since I'm more familiar. Here's the script:
<?php
function queryDB($user, $pass)
{
$connect = new PDO('mysql:host=localhost;dbname=foobar', $user, $pass);
foreach($connect->query("SELECT id, titulo FROM produtos WHERE publicado > 0") as $produto)
{
print($produto['id'].' -> '.$produto['titulo'].'<br>');
$id = $produto['id'];
$assuntos = $connect->query("SELECT id_assunto FROM produtos_tem_assuntos WHERE id_produto = $id");
foreach($assuntos as $assunto_id)
{
foreach($connect->query("SELECT titulo FROM assuntos WHERE id = $assunto_id[0]") as $final)
{
print('<pre>');
var_dump($final[0]);
print('</pre>');
}
}
}
}
print(queryDB('root', 'admin'));
The goal was:
1 - filter the product of a table, and get your id;
2 - use the id of the respective product to filter the subject id (which was in another table);
3 - use the subject id to finally show the subject (which was also in another table).
With the script presented, I was able to return the expected results, but as I'm studying good code practices, I think this script is not the way it should be to perform the tasks described. I even called it gambiarra
.
Then:
What would be the correct way to do these queries?
- how could I have done in phpmyadmin / mysql
- how could I have done the script (if the current one is redundant)
- how refactoring of this code could be done.