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>
|