Echo MySQL结果作为列标题?用PHP

时间:2015-03-30 20:35:16

标签: php mysqli

我有一个表中的日期列表,我想使用php作为列名输出它们

因此,如果表格的值为1,2和3

我想创建一个包含3列,1,2和3作为列名的表

1 个答案:

答案 0 :(得分:0)

<?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>";
}
}

?>

由于答案[此处](https://stackoverflow.com/a/14430366/4680117

,想出了如何做到这一点
相关问题