How to do While from one table and show data from another?

2

I have two tables:

Tabela1: 
 Id int A_I;
 Modelo varchar;

Tabela2:
 Id int A_I;
 Id_fk int (foreign key da tabela1);
 cor;

And I wanted to do a while from table1 but display the data from table2.

<?php
	include 'conn.php';
	mysqli_set_charset($con,"utf-8");
			
	$result = mysqli_query($con,"select * from tabela1");
	$result1 = mysqli_query($con,"select * from tabela2");
			
	while($row = mysqli_fetch_array($result)){
	
        }
        mysqli_close($con);
?>

How do I now show the data?

    
asked by anonymous 26.08.2016 / 11:37

1 answer

4

The solution I left in comment would be the most appropriate:

SELECT * FROM Tabela1 JOIN Tabela2 ON Tabela1.id = Tabela2.Id_fk;

But to be consistent between answer / question here is a solution to what you asked for:

In case that table2 can only have one line with the same Id_fk:

$selTab1 = mysqli_query($conn, "SELECT * FROM tabela1;");
$dataJoin = array();
while ($rowTab1 = $selTab1->fetch_assoc()) {
    $selTab2 = mysqli_query($conn, "SELECT * FROM tabela2 where Id_fk={$rowTab1['id']};");
    if($selTab2->num_rows > 0) {
        $rowTab2 = $selTab2->fetch_assoc();
        $dataJoin[] = array(
            'tab1_id' => $rowTab1['id'],
            'Modelo' => $rowTab1['Modelo'],
            'tab2_id' => $rowTab2['id'],
            'cor' => $rowTab2['cor']
        );
    }
}
echo '<pre>', print_r($dataJoin), '</pre>'; // aqui já vai ter os dados das duas

If table2 can have more than one line with the same Id_fk:

$selTab1 = mysqli_query($conn, "SELECT * FROM tabela1;");
$dataJoin = array();
while ($rowTab1 = $selTab1->fetch_assoc()) {
    $selTab2 = mysqli_query($conn, "SELECT * FROM tabela2 where Id_fk={$rowTab1['id']};");
    while($rowTab2 = $selTab2->fetch_assoc()) {
        $dataJoin[] = array(
            'tab1_id' => $rowTab1['id'],
            'Modelo' => $rowTab1['Modelo'],
            'tab2_id' => $rowTab2['id'],
            'cor' => $rowTab2['cor']
        );
    }
}
echo '<pre>', print_r($dataJoin), '</pre>'; // aqui já vai ter os dados das duas
    
26.08.2016 / 13:02