php - 如何根据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 获取动态列和字段
解决方案
这样做的直接方法是使用结果的键值作为标题,然后将每行数据作为值输出(代码中的注释)......
// 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`
推荐阅读
- python - 数据框:识别系列的百分位值,从其他系列中获取相应的观察值
- python - IndexError:在删除列上使用应用函数时索引超出范围
- ios - UIViewRepresentable 相对于其中的 UIKit 控件如何调整自身的大小?
- ruby-on-rails - 如何计算通过 Mongoid 访问/查询数据库的次数?
- amazon-web-services - 如何从另一个 EBS 类型创建的 AWS 快照创建不同的 AWS EBS 卷
- javascript - 带有 sql 值的 php echo() 中的 javascripts
- java - Java构造函数中计算类属性的约定
- oracle - 错误:在 Crystal Reports 中刷新报表时,“ORA-24374:在获取或执行和获取之前定义未完成”
- java - thymeleaf 模板如何将模型属性与
领域? - mysql-workbench - 如何禁用 MySQL Workbench 的深色主题