使用php和pdo将值获取到td标记中


fetch value into td tag with php and pdo

有了这段代码,我在td标记中看到了文本"Array"。我怎样才能获得真正的价值?

<tbody>
        <tr>
        <?php
        $STH = $DBH->prepare("SELECT * FROM customers");
        $STH->execute();
        $result = $STH->fetchall();
        foreach($result as $key => $value) {
            echo "<td>$value</td>";
        }
        ?>
        </tr>
</tbody>
foreach($result as $key => $value) {
    echo "<td>{$value['field_name']}</td>";
}

这里$value是一个数组,因为$result应该是一个二维数组。所以你需要这样打电话。

echo "<td>{$value['field_name']}</td>";

您可以添加一个额外的foreach

foreach($result as $key => $inner_arr) {
    echo '<tr>';
    foreach($inner_arr as $field_name => $field_value) {
        echo "<td>{$field_value}</td>";
    }
    echo '</tr>';
}

您需要一个额外的层

<tbody>
        <?php
        $STH = $DBH->prepare("SELECT * FROM customers");
        $STH->execute();
        $result = $STH->fetchall();
        foreach($result as $key => $value) {
            echo '<tr>'; // as we have more rows
            // here key is a rownumber value is the full row
            //echo "<td>$value</td>";
            foreach($value as $name => $data) {
              echo "<td>$data</td>";
            }
            echo '</tr>';
        }
        ?>
</tbody>