Echo MySQL 结果作为列标题?在 PHP
Echo MySQL result as column heading? in PHP
我在 table 中有一个日期列表,我想使用 php 作为列名输出它们
所以如果 table 的值为 1,2 和 3
我想创建一个 table 将有 3 列和 1,2 和 3 作为列名
<?php
function db_select_with_col()
{
$rows = array();
$result = db_query("SELECT
student.StudentID,
student.`Name`,
attendance.Date,
CASE WHEN attendance.StudentID IS NOT NULL THEN 'Present' ELSE 'Absent' END as Attendance_Status
FROM
student
Left JOIN attendance ON student.StudentID = attendance.StudentID
WHERE
attendance.Date = '2015-03-30'");
// If query failed, return `false`
if ($result === false) {
return false;
}
// If query was successful, retrieve all the rows into an array
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
$colNames = array_keys(reset($rows));
foreach ($colNames as $colName) {
echo "<th>$colName</th>";
}
foreach ($rows as $row) {
echo "<tr>";
foreach ($colNames as $colName) {
echo "<td>" . $row[$colName] . "</td>";
}
echo "</tr>";
}
}
?>
感谢 [此处] 的回答,弄清楚了如何去做 ()
我在 table 中有一个日期列表,我想使用 php 作为列名输出它们
所以如果 table 的值为 1,2 和 3
我想创建一个 table 将有 3 列和 1,2 和 3 作为列名
<?php
function db_select_with_col()
{
$rows = array();
$result = db_query("SELECT
student.StudentID,
student.`Name`,
attendance.Date,
CASE WHEN attendance.StudentID IS NOT NULL THEN 'Present' ELSE 'Absent' END as Attendance_Status
FROM
student
Left JOIN attendance ON student.StudentID = attendance.StudentID
WHERE
attendance.Date = '2015-03-30'");
// If query failed, return `false`
if ($result === false) {
return false;
}
// If query was successful, retrieve all the rows into an array
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
$colNames = array_keys(reset($rows));
foreach ($colNames as $colName) {
echo "<th>$colName</th>";
}
foreach ($rows as $row) {
echo "<tr>";
foreach ($colNames as $colName) {
echo "<td>" . $row[$colName] . "</td>";
}
echo "</tr>";
}
}
?>
感谢 [此处] 的回答,弄清楚了如何去做 ()