Display data on the same line

0

Hello! I have a table setting another table and I'm trying to display the same content set on the same line.

I did a while but the result looks like this:

André Cargo: Operário
André Cargo: Auxiliar
Julia Cargo: Secretária
Julia Cargo: Auxiliar

I want you to look like this:

André Cargo: Operário e Auxiliar
Julia Cargo: Secretária e Auxiliar
$sql = "select * from funcionarios join cargos on funcionarios.id = cargos.id_funcionario";

$result = mysqli_query($con, $sql);

 while ($row = mysqli_fetch_array($result)) {
  ?>

    <div class="card-stacked">
    <div class="card-content">
      <strong><?php echo $row['nome']; ?></strong>
      <p>Cargo: <?php echo $row['cargo']; ?></p>
  </div>
  </div>


 <?php } ?>
    
asked by anonymous 18.12.2017 / 17:10

1 answer

2

You can use the GROUP_CONCAT function together with GROUP BY in MySQL :

<?php
    $sql = "
        select funcionarios.nome, group_concat(cargos.cargo) as cargo from funcionarios
        join cargos on funcionarios.id = cargos.id_funcionario
        group by funcionarios.id
    ";

    $result = mysqli_query($con, $sql);

    while ($row = mysqli_fetch_array($result)) {
        ?>
            <div class="card-stacked">
                <div class="card-content">
                    <strong><?php echo $row['nome']; ?></strong>
                    <p>Cargo: <?php echo $row['cargo']; ?></p>
                </div>
            </div>    
        <?php
    }
?>

EDIT:

To limit the number of jobs per employee, you will need to change your SELECT to this:

select funcionarios.nome, (
    select group_concat(cargo) from cargos
    where id_funcionario = funcionarios.id
    limit 2
) as cargo
from funcionarios
    
18.12.2017 / 17:39