当我使用setFetchMode(PDO :: FETCH_ASSOC)时,为什么rowcount和结果不会同时显示

时间:2015-08-07 18:01:31

标签: php mysql pdo

好吧,我正在尝试查询一些数据并显示结果,还会看到row_count。以下是我正在使用的代码:

    <?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "db_xx";



    try {
     $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

     $sql = 'SELECT * FROM tbl_registration_requests where FLAG_ACCEPTANCE="0"';

     $q = $conn->query($sql);
     $q->setFetchMode(PDO::FETCH_ASSOC);


     $rows = $q->fetchAll();
    $num_rows = count($rows);


    } catch (PDOException $pe) {
     die("Could not connect to the database $dbname :" . $pe->getMessage());
    }
    ?>

并在table ::

中显示
<table id="table_reg_confirm" border="1"  cellpadding="5px" ">
         <thead bgcolor="#999999">
             <tr>
             <th>ID</th>
             <th>First Name</th>
             <th>Last Name</th>
             <th>Email</th>
             <th>Phone</th>
             <th>Address</th>
             <th>Date Of Birth</th>
             <th>Comments</th>                               
             </tr>
         </thead>

         <tbody>

             <?php while ($r = $q->fetch()): 
                $i=0;
             ?>
                 <tr>
                     <td><?php echo htmlspecialchars($r['ID'])?></td>
                      <td><input type="text" name="frname".<?php $i; ?> value="<?php echo htmlspecialchars($r['FIRST_NAME']).$i?> "></td>
                     <td><?php echo htmlspecialchars($r['LAST_NAME']); ?></td>
                     <td><?php echo htmlspecialchars($r['EMAIL']); ?></td>
                     <td><?php echo htmlspecialchars($r['PHONE']); ?></td>
                     <td><?php echo htmlspecialchars($r['ADDRESS']); ?></td>
                     <td><?php echo htmlspecialchars($r['DOB']); ?></td>
                     <td><?php echo htmlspecialchars($r['COMMENTS']); ?></td>
                 </tr>
             <?php  endwhile; ?>

         </tbody>

 </table>

要查看row_count ::

 <?php  echo $num_rows; ?>

但是每当我使用$rows = $q->fetchAll(); $num_rows = count($rows);进行row_count-时,结果表都没有显示。它出什么问题了?除了这两行外,结果显示正常。

1 个答案:

答案 0 :(得分:0)

更改while循环行以使用foreach:

<?php foreach($rows as $r): ?>
...
 <?php  endforeach; ?>

您必须使用$ rows数组变量中捕获的行。在已经提取一次后,你无法从pdo处理程序中获取行。