2014-01-20 91 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> 
相關問題