PDO中獲取結果集之fetch()方法詳解


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);//初始化一個PDO對象,就是創建了數據庫連接對象$pdo

    $query="select * from user";//需要執行的sql語句

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM