2014-01-20 57 views
0

我正在写一些从数据库呈现表格的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> 

如果有人能告诉我,为什么它是空的,为什么有多余的细胞,这将不胜感激。

+0

不知道您的登录信息是正确的,但我已经删除了您的登录凭据,以防万一用占位符代替它们。 – Lee

+0

请在fectAll后打印这个 var_dump($ result): –

+0

你认为你正在用嵌套循环完成什么?为什么要获取整个结果集而不是从结果集中一次显示一行(根据结果集的大小,您的方法可能会占用更多的内存)。 –

回答

0

下面的代码使用while()循环,而不是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> 
相关问题