Group repeated fields of a MySQL query with PHP

1

I have an intermediate table (N: M) in MySQL where I store the idProfesor and idMateria , when recovering the data from PHP it returns me 5 rows:

id | idMateria | idProfesor
---+-----------+-----------
1  | 1         | 1
2  | 2         | 1
3  | 3         | 1
4  | 2         | 2
5  | 3         | 2 

What I want to know is how to show in the PHP view only the id of teacher 1, his 3 subjects he gives, then the id of professor 2 and his two subjects he gives, but that the teacher id just leave once .

Example:

idProfesor = 1
----------------
idMateria  = 1
idMateria  = 2
idMateria  = 3


idProfesor = 2
------------------
idMateria  = 2
idMateria  = 3
    
asked by Oscar Bautista 12.12.2017 в 05:27
source

1 answer

3

Do not group in the query, basically do a conditional in the while while traversing the rows in php, example:

$idProfesor = 0;
while ( $result = /* fetch */ ) {
    // Compruebas si es diferente para mostrarlo o no
    if ($idProfesor != $result['idProfesor']) {
        echo $result['idProfesor'];
        // asignas el nuevo id
        $idProfesor = $result['idProfesor'];
    }
    // Muestra las materias
    echo $result['materia'];

    /* RESTO DEL while */
}
    
answered by 12.12.2017 / 13:59
source