Latest web development tutorials

PDOStatement::setFetchMode

PHP PDO 參考手冊 PHP PDO參考手冊

PDOStatement::setFetchMode — 為語句設置默認的獲取模式。 (PHP 5 >= 5.1.0, PECL pdo >= 0.2.0)


說明

語法

bool PDOStatement::setFetchMode ( int $mode )
bool PDOStatement::setFetchMode ( int $PDO::FETCH_COLUMN , int $colno )
bool PDOStatement::setFetchMode ( int $PDO::FETCH_CLASS , string $classname , array $ctorargs )
bool PDOStatement::setFetchMode ( int $PDO::FETCH_INTO , object $object )

參數

mode
獲取模式必須是PDO::FETCH_* 系列常量中的一個。

colno
列號。

classname
類名。

ctorargs
構造函數參數。

object
對象。


返回值

成功時返回TRUE, 或者在失敗時返回FALSE。


實例

設置獲取模式

下面的例子示範如何用PDOStatement::setFetchMode() 來為一個PDOStatement 對象更改默認的獲取模式。

<?php
$sql = 'SELECT name, colour, calories FROM fruit';
try {
  $stmt = $dbh->query($sql);
  $result = $stmt->setFetchMode(PDO::FETCH_NUM);
  while ($row = $stmt->fetch()) {
    print $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
  }
}
catch (PDOException $e) {
  print $e->getMessage();
}
?>

以上實例輸出為:

apple   red     150
banana  yellow  250
orange  orange  300
kiwi    brown   75
lemon   yellow  25
pear    green   150
watermelon      pink    90

PHP PDO 參考手冊 PHP PDO參考手冊