fetch()方法获取结果集中的下一行数据,该函数的具体语法格式如下:大理石平台检定规程
| 
 1 
 | 
mixed PDOStatement::fetch ([ int $fetch_style [, int $cursor_orientation = PDO::FETCH_ORI_NEXT [, int $cursor_offset = 0 ]]] ) 
 
 | 
参数 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种形式返回结果。 | 
参数 cursor_orientation:PDOStatement对象的一个滚动游标,可以获取指定的一行。
参数 cursor_offset:游标的偏移量。
下面实例通过 fetch()方法获取结果集中下一行的数据,进而应用 while 语句完成数据库中数据的循环输出,步骤如下:
首先创建一个php文件,通过 PDO连接MySQL数据库,然后定义 SELECT查询语句,应用prepare()和execute()方法执行查询操作,接着,通过fetch()方法返回结果集中下一行数据没同事设置结果集以关联数组形式返回,最后通过 while语句完成数据的循环输出,具体代码如下:
| 
 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 
 | 
<?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=new PDO($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 
    while($result=$res->fetch(PDO::FETCH_ASSOC)){          
        ?> 
        <tr> 
        <td height="22" align="center" valign="middle"><?php echo $result["id"];?></td> 
        <td height="22" align="center" valign="middle"><?php echo $result["username"];?></td> 
        <td height="22" align="center" valign="middle"><?php echo $result["password"];?></td> 
        </tr> 
<?php 
    } 
}catch(Exception $e){ 
    die("Error!:".$e->getMessage().'<br>'); 
} 
?> 
</table> 
 
 |