从mysql查询中翻转表并在php中输出

时间:2017-01-21 19:15:56

标签: php mysql

我试图在php mysql的输出中反转一个表。运行以下代码将垂直打印所有标题,并在其下方垂直打印所有数据。

Expected output :
Name -- xxx
DoB --- xxx
Gender - xxx
Email -- xxx
Phone -- xxx
Address - xx

<table id="myTable">
    <tr><th>Name</th></tr>      
    <tr><th>DoB</th></tr>
    <tr><th>Gender</th></tr> 
    <tr><th>Email</th></tr>
    <tr><th>Phone</th></tr>
    <tr><th>Address</th></tr>                       

    <?php
        while ($report=$result->fetch_assoc())  
        {
        echo "<tr><td>".$report['name']."</td>";                
        echo "<tr><td>".$report['dob']."</td>"; 
        echo "<tr><td>".$report['gender']."</td>"; 
        echo "<tr><td>".$report['email']."</td>"; 
        echo "<tr><td>".$report['phone']."</td>"; 
        echo "<tr><td>".$report['address']."</td>"; 
        }
    ?>
</table>

1 个答案:

答案 0 :(得分:0)

鉴于您将表格垂直显示,并且您希望将此表格水平显示,解决方案将如下所示:

<table id="myTable">
    <?php
        $fields = $result->fetch_fields();
        foreach($fields as $field){
            echo '<tr>';
                echo '<td>' . $field->name . '</td>';
                while($report = $result->fetch_assoc()){
                    echo '<td>' . $report[$field->name] . '</td>';
                }
                $result->data_seek(0);
            echo '</tr>';
        }
    ?>
</table>