fetchAll()方法是獲取結果集中的所有行,返回一個包含結果集中所有行的二進制數組!大理石機械構件維修廠家
那么在上一篇《PDO中獲取結果集之fetch()方法詳解》中,我們介紹了fetch()方法獲取結果集,我們今天將要介紹的fetchAll()方法與上一個方法fetch()類似,但是該方法只需要調用一次就可以獲取結果集中的所有行,並賦給返回的數組(二維)。
fetchAll()方法的語法格式如下:
| 1 |
array PDOStatement::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=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
$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>
|