Php MYSQL query multiple tables [closed]

-1

Well, I'm having trouble displaying data from a database using 3 tables.

<?php
include("conectar.php");

$quantidade = 1;
$pagina = (isset($_GET['pagina'])) ? (int)$_GET['pagina'] : 1;
$inicio = ($quantidade * $pagina)-$quantidade;  
$sql = "Select * From tb_trabalhador order by id asc LIMIT $inicio, $quantidade";
$qr = mysql_query($sql) or die (mysql_error());
    while($exibe = mysql_fetch_array($qr)){

I have 2 more tables to display the data that is there. I just ran the test with two tables and it also does not display the entered data.

 SELECT * FROM tb_trabalhador
 INNER JOIN tb_detalhe_trabalhador ON Tb_trabalhador.id     =tb_detalhe_trabalhador.tb_trabalhador_id;

I tried the Left and Right and displays the data of the respective tables. Can you help me with this problem?

    
asked by anonymous 20.02.2014 / 16:26

3 answers

3

Use a join to join the tables and access all the fields you need:

SELECT * FROM tb_trabalhador as t
INNER JOIN tb_equipamentos as e ON t.id = e.trabalhador_id
INNER JOIN tb_detalhe_trabalhador as d ON t.id = d.tb_trabalhador_id

instead of asterics * put the required fields in the format tabela.nome_do_campo or alias.nome_do_campo

Ex:

SELECT e.marca, e.modelo, t.nome, t.matricula, d.outro_campo FROM ....
INNER ....

Related Content: difference between INNER X OUTER

    
20.02.2014 / 16:33
1

To illustrate the use of the JOIN as @ lost said, follow

<?php
include("conectar.php");

$quantidade = 1;
$pagina = (isset($_GET['pagina'])) ? (int)$_GET['pagina'] : 1;
$inicio = ($quantidade * $pagina)-$quantidade;  
$sql = "SELECT * FROM tb_trabalhador as t ".
        " INNER JOIN tb_equipamentos as e ON t.id = e.trabalhador_id "
        " INNER JOIN tb_detalhe_trabalhador as d ON t.id = d.tb_trabalhador_id order by id asc LIMIT $inicio, $quantidade";
$qr = mysql_query($sql) or die (mysql_error());
  while($exibe = mysql_fetch_array($qr)){

If the tp_equipamento table is not always mandatory, that is, it may not have been related to tp_trabalhador , you will have to use LEFT JOIN

    
20.02.2014 / 16:40
0

Very simple way using the join in the WHERE clause

<?php
include("conectar.php");

$quantidade = 1;
$pagina = (isset($_GET['pagina'])) ? (int)$_GET['pagina'] : 1;
$inicio = ($quantidade * $pagina)-$quantidade;  
$sql = "SELECT * FROM tb_trabalhador as t, tb_equipamentos e , tb_detalhe_trabalhador d ".
       " WHERE t.id = e.trabalhador_id AND t.id = d.tb_trabalhador_id ".
       " order by id asc LIMIT $inicio, $quantidade";
$qr = mysql_query($sql) or die (mysql_error());
  while($exibe = mysql_fetch_array($qr)){
    
20.02.2014 / 16:53