PHP / MySQL - Print values relative to tables

0

In a system I need to print ink cans and each one has its own colors. I did it in a way that works, but it repeats the requests in the database several times.

I made two tables (Example):

latas
______________
id | nome
1  | uso geral
2  | teste 1
3  | teste 2


cores
__________________________
id | nome | hexa | id_lata
1  | azul | #0495| 1
2  | preto | #000| 1

My code is more or less so at the moment:

<?php
$sql_latas = mysqli_query($conn, 'SELECT * FROM latas');
while($row_latas = mysqli_fetch_array($sql_latas)){
?>
   <div class="lata">
      <span><?php echo $row_latas['nome']; ?></span>
   </div>

   <ul class="cores">

      <?php
      $sql_cores = mysqli_query($conn, 'SELECT * FROM cores WHERE id_lata = '.$row_latas['id']);
      while($row_cores = mysqli_fetch_array($sql_cores)){
      ?>

         <li><?php echo $row_cores['nome']; ?></li>

      <?php
      }
      ?>

   </ul>
<?php
}
?>

How can I do this?

    
asked by anonymous 13.09.2016 / 16:43

1 answer

1

You can only construct a SQL, using JOIN to join the tables based on id_lata , in this case, you will get the results of each of the tables, and also to distinguish one column from the other, you can SELECT, set what is the column and what name will be represented, like the example below:

SELECT 
    latas.nome as nome_lata,
    cores.nome as cor_lata,
FROM latas
JOIN cores ON(cores.id_lata=latas.id)


while($row=mysqli_fetch_assoc($sql)){
    echo $row['nome_lata'];
    echo $row['cor_lata']."<br><br>";
}
    
13.09.2016 / 16:54