试图在表格中显示列的内容,但我不知道会有多少列

时间:2013-11-16 00:03:44

标签: php mysql pdo

到目前为止,我已经有了这段代码来显示列:

$st = $db_pdo->prepare("DESCRIBE email");
$st->execute();
$rows = $st->fetchAll(PDO::FETCH_COLUMN);
$column_array = array();

foreach ($rows as $row=>$key){
    echo '<strong>'. strtoupper($key) . '</strong><br>'; 
}

假设我们在db中有以下格式:

-------------------
| column1| column2|
|--------|--------|
| content|content |
|        |        |
|        |        |

依此类推。

我想显示列的内容。就是这样,没有别的,不修改它们,只显示内容。

2 个答案:

答案 0 :(得分:0)

$stmt = $db_pdo->prepare("SELECT * FROM email");
$stmt->execute();
echo '<table>';
$first_row = true;
while ($row = $stmt->fetchAssoc()) {
    if ($first_row) {
        echo '<tr>';
        foreach (array_keys($row) as $column_name) {
            echo '<th>' . htmlentities($column_name) . '</th>';
        }
        echo '</tr>';
        first_row = false;
    }
    echo '<tr>';
    foreach ($row as $content) {
        echo '<td>' . htmlentities($content) . '</td>';
    }
    echo '</tr>';
}
echo '</table>';

答案 1 :(得分:0)

try {
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); // Exclude the index count from the fetched array (the row).

    $stmt = $pdo->prepare('select * from email'); // You really don't need to put statements in uppercase (where are we in 1980?)
    $stmt->execute();
    while ($row = $stmt->fetch()) { // You need to loop and fetch the row to get the content.

         foreach ($row as $key => $val){
         echo '<strong>'. strtoupper($val) . '</strong><br>'; // Replaced $key to $val to get the content.
        }
    }
}
catch (PDOException $e) {
die(htmlspecialchars($e->getMessage()));
}