首页 > 解决方案 > 如何根据mysql中的选定列动态更改html表列

问题描述

我有多个选择选项。但是,当我选择 1 个或两个选项或任何其他选项时,我想<th></th>动态更改 html 的列并从数据库中获取数据

目前我已经创建了多选选项和 html 表

<select class="selectpicker" id="sensor" name="sensor[]" multiple>
                                <option 
     value="temperature">Temperature</option>
                                <option value="humidity">Humidity</option>
                                <option value="presure">Presure</option>
                                <option 
     value="level">Level</option>
                                </select>

     $query = "SELECT ".$selectedSensorOption." from p1";       
                    $result = $db_handle->runQuery($query);
    foreach ($result as $key => $value) {
    <table>
    <tr>
    <th>$result</th>
    </tr> 
    <tr>
    <td>$result</td>

我还想根据多个选择选项从 MySQL db 获取动态列和字段

标签: phphtmlmysql

解决方案


这样做的直接方法是使用结果的键值作为标题,然后将每行数据作为值输出(代码中的注释)......

// Output table start and header row
echo "<table><tr>";
// Use the first rows results as the header values
foreach ( $result[0] as $header => $value ) {
    echo "<th>{$header}</th>";
}
echo "</tr>";
// Output each data row
foreach ($result as $values) {
    echo "<tr>";
    // Loop over each item in the row and output the value
    foreach ( $values as $value ) {
        echo "<td>{$value}</td>";
    }
    echo "</tr>";
}
echo "</table>";  

您可以创建更短的代码(使用implode()等),但有时更简单的代码更容易开始和维护。

使用返回的列名意味着您可以使用列别名来使用特定的标题——比如

id as `User ID`, fullname as `Name`

推荐阅读