sql >> Base de Datos >  >> RDS >> Mysql

Mysql muestra filas como columnas

Primero debe transponer todos los datos en una matriz temporal antes de poder generarlos nuevamente. Te daré 2 métodos para hacer esto.

Método 1:solo busca cada fila y cambia el índice de la fila por el índice de la columna:

<table>
    <tr>
        <th>Subject</th>
        <th>year1</th>
        <th>year2</th>
        <th>year3</th>
    </tr>

    <?php
    $mysqli = new mysqli('localhost', 'user', 'pass', 'database');
    $id = 1;
    $report = array();
    $columnIndex = 0;
    $query = $mysqli->query("SELECT HTML, CSS, Js FROM term WHERE Stdid='$id'");
    while ($results = $query->fetch_assoc()) {
        foreach ($results as $course => $score) {
            $report[$course][$columnIndex] = $score;
        }
        $columnIndex++;
    }

    foreach ($report as $course => $results) { ?>
        <tr>
            <th><?php echo $course; ?></th>
            <?php foreach ($results as $score) { ?>
                <th><?php echo $score; ?></th>
            <?php } ?>
        </tr>
    <?php } ?>
</table>

Método 2:obtenga todas las filas en una matriz, de modo que se convierta en una matriz de matrices y use array_map con devolución de llamada NULL para transponerlo (Ver ejemplo 4 en http://php.net/manual /es/function.array-map.php ). Debe agregar los nombres de los cursos en la matriz inicial para incluirlos en el resultado final.

<table>
    <tr>
        <th>Subject</th>
        <th>year1</th>
        <th>year2</th>
        <th>year3</th>
    </tr>

    <?php
    $mysqli = new mysqli('localhost', 'user', 'pass', 'database');
    $id = 1;
    $data = array(array('HTML', 'CSS', 'Js'));
    $query = $mysqli->query("SELECT HTML, CSS, Js FROM term WHERE Stdid='$id'");
    while ($row = $query->fetch_assoc())
    {
        $data[] = $row;
    }
    $data = call_user_func_array('array_map', array_merge(array(NULL), $data));
    ?>

    <?php
    foreach ($data as $row): ?>
        <tr>
            <?php foreach ($row as $value): ?>
                <th><?php echo $value?></th>
            <?php endforeach; ?>
        </tr>
    <?php endforeach; ?>
</table>