【问题标题】:Why is my table being rendered empty?为什么我的桌子是空的?
【发布时间】:2014-02-10 08:26:53
【问题描述】:

我正在编写一些从数据库呈现表格的 php,这应该很简单,但由于某种原因,它正在呈现额外的单元格并且所有单元格都是空的。这是我的代码:

<?php
    $db= new PDO("mysql:host=localhost;dbname=mydb", "user", "password");
    $query= $db->query("SELECT yarnId, yarnName, longYarnDescription, sale_price, cost, contents, onSale, yarnImage, activeFlag FROM yarn"); 
    $result= $query->fetchAll();
?>
<table border="1">
   <tr>
    <th>yarnId</th>
    <th>yarnName</th>
    <th>description</th>
    <th>sale price</th>
    <th>cost</th>
    <th>contents</th>
    <th>onSale</th>
    <th>yarnImage</th>
    <th>activeFlag</th>
    <th>edit</th>
   </tr>
   <?php for($r=0; $r<count($result); $r++){?>
    <tr>
        <?php for($c=0; $c<count($result[0]); $c++){?>
            <td><?php echo $result[r][c];?></td>
        <?php }?>
        <td><button name=edit>edit</button></td>
    </tr>
   <?php }?>
</table> 

如果有人能告诉我为什么它是空的以及为什么有多余的单元格,将不胜感激。

【问题讨论】:

  • 不确定您的登录信息是否正确,但我已删除您的登录凭据并用占位符替换它们以防万一。
  • 请在 fectAll var_dump($result) 之后打印:
  • 你认为你用嵌套循环完成了什么?为什么要获取整个结果集而不是从结果集中一次显示一行(根据结果集的大小,您的方法可能会占用更多内存)。
  • 数组的内容是正确的,所以不是数据库或者它的查询的问题。
  • &lt;td&gt;&lt;?php echo $result[r][c];?&gt;&lt;/td&gt; 应该是&lt;td&gt;&lt;?php echo $result[$r][$c];?&gt;&lt;/td&gt;

标签: php mysql pdo render


【解决方案1】:

以下代码使用while()loop 代替for()

<table border="1">
   <tr>
    <th>yarnId</th>
    <th>yarnName</th>
    <th>description</th>
    <th>sale price</th>
    <th>cost</th>
    <th>contents</th>
    <th>onSale</th>
    <th>yarnImage</th>
    <th>activeFlag</th>
    <th>edit</th>
   </tr>
<?php 
while($row = $query->fetch()) { 
    echo "<tr>"; 
    for ($x=0;$x<= 8; $x++)  {
        echo "<td>" . $row[$x] . "</td>";
    }
    echo "<td><button name=\"edit\">edit</button></td></tr>\n";
}
?>
</table> 

【讨论】:

    猜你喜欢
    • 2011-08-01
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多