【问题标题】:Displaying mysql data in html table PHP在 html 表 PHP 中显示 mysql 数据
【发布时间】:2014-03-24 18:48:53
【问题描述】:

我必须将 MySQL 表中的数据显示在 HTML 表中。 我的代码将显示 MySQL 表中七行中的第一行,但它重复该行九次,而不是显示所有七行。 我做错了什么?

<?php
require 'database.php';

//get all product data
$query = 'SELECT * FROM products';
          $products = $db->query($query);
          $products = $products->fetch();
?>

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>SportsPro</title>
    </head>

    <body>
    <form id="Header" name="Header" method="post">
    <?php include 'header.php'; ?>
    </form>
    <form id="Content" name="Content" method="post">
    <table width="500" border="1">
    <tr>
    <th scope="col">Code</th>
    <th scope="col">Name</th>
    <th scope="col">Version</th>
    <th scope="col">Release Date</th>
    <th scope="col">&nbsp;</th>
    </tr>
    <?php foreach ($products as $product) { ?>
    <tr>
    <td><?php echo $products['productCode']; ?></td>
    <td><?php echo $products['name']; ?></td>
    <td><?php echo $products['version']; ?></td>
    <td><?php echo $products['releaseDate']; ?></td>
    <td><input type = "submit" value = "Delete" align = "right" ></td>

    </tr> 
    <?php } ?>
    </table>

    <p><a href="add_product.php">Add Product</a></p>
    </form>
    <form id="Footer" name="Footer" method="post">
    <?php include 'footer.php'; ?>
    </form>
    </body>
    </html>

【问题讨论】:

  • 查看var_dump($products);的结果

标签: php mysql html-table


【解决方案1】:

您为什么使用 $products?

修复:

<?php 
foreach ($products as $product) {  //See *$products as $product*, so no need to use $products below instead use $product
    echo "<tr>";
    echo "<td>". $product['productCode']. "</td>";
    echo "<td>". $product['name']. "</td>";
    echo "<td>". $product['version']. "</td>";
    echo "<td>". $product['releaseDate']. "</td>";
    echo "<td><input type = \"submit\" value = \"Delete\" align = \"right\" ></td>";
    echo "</tr>" 
} 
?>

【讨论】:

    【解决方案2】:

    你必须更换,

    $products = $products->fetch(); 
    

    $products = $products->fetchAll();
    

    在 td 标签内,你有,

    <?php echo $products['productCode']; ?>
    

    将所有行更改为如下所示,

    <?php echo $product['productCode']; ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-22
      • 1970-01-01
      • 2016-10-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-21
      相关资源
      最近更新 更多