fetchAll()方法是获取结果集中的所有行,返回一个包含结果集中所有行的二进制数组!大理石机械构件维修厂家
那么在上一篇《PDO中获取结果集之fetch()方法详解》中,我们介绍了fetch()方法获取结果集,我们今天将要介绍的fetchAll()方法与上一个方法fetch()类似,但是该方法只需要调用一次就可以获取结果集中的所有行,并赋给返回的数组(二维)。
fetchAll()方法的语法格式如下:
| 1 | 
arrayPDOStatement::fetchAll ([ int $fetch_style[, mixed $fetch_argument[, array$ctor_args= array() ]]] )
 | 
参数 fetch_style:控制结果集中数据的返回方式,可选值如下表:
| 值 | 说 明 | 
| PDO::FETCH_ASSOC | 关联数组形式 | 
| PDO::FETCH_NUM | 数字索引数组形式 | 
| PDO::FETCH_BOTH | 两者数组形式都有,这是默认的 | 
| PDO::FETCH_OBJ | 按照对象的形式,类似于以前的mysql_fetch_object() | 
| PDO::FETCH_BOUND | 以布尔值的形式返回结果,同时将获取的列值赋给bindParam()方法中指定的变量 | 
| PDO::FETCH_LAZY | 以关联数组、数字索引数组和对象3种形式返回结果。 | 
参数 column_index:字段的索引!
其返回值是一个包含结果集中所有数据的二维数组。
下面我们通过 fetchAll()方法获取结果集中的所有行,并且通过 for 语句读取二维数组中的数据,完成数据库中数据的循环输出,具体步骤如下:
首先创建php文件,通过 PDO 连接MySQL 数据库,然后定义 SELECT查询语句,应用 prepare()和execute()方法执行查询操作,接着,通过fetchAll()方法返回结果集中的所有行,最后使用 for 语句完成结果集中所有数据的循环输出,代码如下:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 
<?php
 header("Content-Type:text/html; charset=utf-8");    
 $dbms= "mysql";                                  
 $dbName="php_cn";                                
 $user= "root";                                   
 $pwd= "root";                                    
 $host= "localhost";                              
 $dsn= "$dbms:host=$host;dbname=$dbName";
 try{
     $pdo=newPDO($dsn,$user,$pwd);
     $query="select * from user";
     $res=$pdo->prepare($query);
     $res->execute();            
     ?>
     <table border="1"width="500">
         <tr>
             <td height="22"align="center"valign="middle">id</td>
             <td height="22"align="center"valign="middle">用户名</td>
             <td height="22"align="center"valign="middle">密码</td>
         </tr>
         <?php
   $result=$res->fetchAll(PDO::FETCH_ASSOC) ;        
         for($i=0;$i<count($result);$i++){          
         ?>
         <tr>
         <td height="22"align="center"valign="middle"><?php echo$result[$i]['id'];?></td>
         <td height="22"align="center"valign="middle"><?php echo$result[$i]['username'];?></td>
         <td height="22"align="center"valign="middle"><?php echo$result[$i]['password'];?></td>
         </tr>
 <?php
     }
 }catch(Exception $e){
     die("Error!:".$e->getMessage().'<br>');
 }
 ?>
 </table>
 |