1
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 relational tables, with the respective indexes. But I don’t know much about mysql, I even tried to use the relational tables in phpmyadmin, but I didn’t know how to.
What to do? Obviously I would not sit idly by in front of the pc, so I tried to come up with a solution with a PHP script, since I am more familiar. Here is 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 from a table, and get its id;
2 - use the respective product id 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 presented script, I managed to return the expected results, but as I am studying good code practices, I think this script is not in the way it should be to perform the described tasks. I even called it gambiarra
.
So:
What would be the right way to make these queries?
- as I could have done in phpmyadmin/mysql
- as I could have done the script (in case the current one is redundant)
- how this code could be refactored.
could you give me some reference of these methods? a link would be great! , and how you would do the refactoring of this code using JOIN?
– wdarking
A good start => What is the difference between INNER JOIN and OUTER JOIN?
– rray
opa! vlw! I was already reading http://dev.mysql.com/doc/refman/5.7/en/join.html, but I find mysql’s Docs very confusing! It helped me :)
– wdarking