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

时间:2013-08-28 08:58:22

标签: php mysql pdo

使用此代码,我在td-tag内部显示文本“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>

2 个答案:

答案 0 :(得分:3)

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>';
}

答案 1 :(得分:0)

您需要一个额外的图层

<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>