试图显示数据库表中的每一行,但只显示第一行

时间:2014-04-01 21:09:53

标签: php mysql pdo

我在我的数据库中有一个表“类别”,我有这个:enter image description here

现在使用php Im显示没有“father”的类别,换句话说,id_father为null时的类别。像警告和技术一样。

我这样做:

<div class="block cat" style="display:block">
        <div class="title">Categories:</div>   
         <?php
            $readCat = $pdo->prepare("SELECT * FROM categories where id_father IS null");  
            $readCat->execute();
            $num_rows_readCat = $readCat->rowCount();
            $readCategoriesResult = $readCat->fetch(PDO::FETCH_ASSOC);
            if(!$num_rows_readCat >= 1)
            {
                echo 'There is no categories registers yet.';
            }
            else
            {       
         ?>                            
        <table width="560">
          <tr class="cts">
            <td>category Name:</td>
            <td>Content</td>
            <td>tags:</td>
            <td>Date:</td>
          </tr>
          <?php
                    foreach($readCategoriesResult as $cat)
            echo '<tr>';
            echo '<td>'.$cat['name'].'</td>';
            echo '<td>'.$cat['content'].'</td>';
            echo '<td align="center"><img src="ico/ok.png" alt="3 Tags" title="3 Tags" /></td>';
            echo '<td align="center">'.date('d/m/Y H:i',strtotime($cat['date'])).'</td>';
            echo '</tr>';

它的工作正常,我已经有了第一类“警告”。

但我只有第一个类别,我想显示我在数据库中的每个类别,在这种情况下我也有技术,但它只显示警告类别。

我alraedy尝试使用foreach循环,但它不起作用......

有人看到问题在哪里?

4 个答案:

答案 0 :(得分:2)

while ($row = $readCat->fetch(PDO::FETCH_ASSOC)) {
echo '<tr>';
        echo '<td>'.$row['name'].'</td>';
        echo '<td>'.$row['content'].'</td>';
        echo '<td align="center"><img src="ico/ok.png" alt="3 Tags" title="3 Tags" /></td>';
        echo '<td align="center">'.date('d/m/Y H:i',strtotime($row['date'])).'</td>';
        echo '</tr>';
}

while循环表示将返回的所有行都将被回显。

答案 1 :(得分:2)

$readCat->fetch(PDO::FETCH_ASSOC);只会获取一个结果。你需要:

  1. 使用$readCat->fetchAll(PDO::FETCH_ASSOC);并使用foreach循环,如上所述。
  2. 在while循环中使用$readCat->fetch(PDO::FETCH_ASSOC);
  3. 这里是while循环:

    while ($result = $readCat->fetch(PDO::FETCH_ASSOC)){
        //Echo HTML here
    }
    

答案 2 :(得分:2)

如果你想获得所有记录,你需要做一个fetchAll然后循环记录:

$readCategoriesResult = $readCat->fetchAll(PDO::FETCH_ASSOC);

...

foreach($readCategoriesResult as $cat){
    //display the table row
}

或者,您可以在while循环中fetch,但我喜欢fetchAll

答案 3 :(得分:1)

  

有人看到问题在哪里?

问题是缺少foreach循环,并且可能在fetch方法之间存在一些混淆。你可以在tag wiki

中阅读