Display data in the same row

Asked

Viewed 210 times

0

Hello! I have a table setting another table and I’m trying to display the same content set in the same row.

I did a while but the result is getting like this:

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

I want it to stay that way:

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 } ?>
  • 1

    Need to put your SQL or PHP code to know exactly where to move.

  • I put the code.

1 answer

2


You can use the function GROUP_CONCAT together with the GROUP BY in the 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 amount of jobs per employee, you will have to change your SELECT for that reason:

select funcionarios.nome, (
    select group_concat(cargo) from cargos
    where id_funcionario = funcionarios.id
    limit 2
) as cargo
from funcionarios
  • That’s right. In case agr how I would do to limit the positions to show only 2 per person?

  • I edited the answer by putting the limit.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.