0

I have three tables:

  • users (primary key: id_users)
  • centers (primary key: id_centers)
  • usersInCenters (primary key: id_usersInCenters, foreign keys: id_users and id_centers)

With the third table I connect the users with the centers, because 1 user can attend to different centers.

And with this SELECT I get the result that I want:

 SELECT *
 FROM `userInCenter`
 RIGHT JOIN `user` ON `user`.`id_user` = `userInCenter`.`id_user`
 ";

With this query I get:

enter image description here

So, this is actually pretty good, and almost achieved what I want.

The only thing, is that my query creates two rows if one user has two centers.

But, what I want, is to display one row and show the centers in the same field: 8,7. Like this.

Is this possible? Or do I have to change something?

FIDDLE: http://sqlfiddle.com/#!9/0fed10/2

PHP:

        <?php 
    while ($row=mysqli_fetch_object($listaDeUsuarios)){

        $id_usuario=$row->id_usuario;
        $nombreUsuario=$row->nombreUsuario;
        $apellidoUsuario=$row->apellidoUsuario;
        $emailUsuario=$row->emailUsuario;
        $ciudadUsuario=$row->ciudadUsuario;
        $createdAt=$row->createdAt;
        $id_centroDeportivo=$row->id_centroDeportivo;
         ?>

Thanks in advance Alejandro.

1 Answers1

0
<?php
$con = mysqli_connect("localhost", "root", "", "gymtable_test");

//Retrieving the contents of the table
$res = mysqli_query($con, "SELECT ucd.id_usuarioCentroDeportivo, ucd.id_usuario, GROUP_CONCAT(ucd.id_centroDeportivo SEPARATOR ',') AS id_centroDeportivo, ucd.rolUsuarioCentro, ucd.createdAt, u.*
FROM usuarioCentroDeportivo ucd
RIGHT JOIN usuario u ON u.id_usuario = ucd.id_usuario
GROUP BY ucd.id_usuario");

//Fetching all the rows as objects
while ($row=mysqli_fetch_object($res)){
    $id_usuario=$row->id_usuario;
    $nombreUsuario=$row->nombreUsuario;
    $apellidoUsuario=$row->apellidoUsuario;
    $emailUsuario=$row->emailUsuario;
    $ciudadUsuario=$row->ciudadUsuario;
    $createdAt=$row->createdAt;
    $id_centroDeportivo=$row->id_centroDeportivo;
    // do something with the variables
}
//Closing the statement
mysqli_free_result($res);

//Closing the connection
mysqli_close($con);

GROUP BY groups together rows with the same user id (ucd.id_usuario), GROUP_CONCAT then displays all the centers for each user id separated with a comma.

Marleen
  • 2,245
  • 2
  • 13
  • 23