10
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PDOのfetchModeを比較してみた

Last updated at Posted at 2015-01-11

PDOはfetchModeを指定してデータを扱いやすい形に変換することができる。

fetchModeのデフォルトは$PDO::FETCH_BOTHに設定されている。
今回は下記5つについて表示させてみる。

  1. FETCH_BOTH
  2. FETCH_COLUMN
  3. FETCH_CLASS
  4. FETCH_INTO
  5. FETCH_ASSOC

下記のようなデータをそれぞれのfetchModeでフェッチして表示させてみた。

nyc=# SELECT * FROM pdo_study;
 id |  name  
----+--------
  1 | りんご
  2 | みかん
(2 )
// $stmt->setFetchMode(PDO::FETCH_BOTH); 
// これがデフォルト
array(4) {
  ["id"]=>
  int(1)
  [0]=>
  int(1)
  ["name"]=>
  string(9) "りんご"
  [1]=>
  string(9) "りんご"
}
array(4) {
  ["id"]=>
  int(2)
  [0]=>
  int(2)
  ["name"]=>
  string(9) "みかん"
  [1]=>
  string(9) "みかん"
}
// $stmt->setFetchMode(PDO::FETCH_COLUMN, 1);
// 第二引数はカラム番号
string(9) "りんご"
string(9) "みかん"
// $stmt->setFetchMode(PDO::FETCH_CLASS, 'stdClass');
object(stdClass)#3 (2) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(9) "りんご"
}
object(stdClass)#5 (2) {
  ["id"]=>
  int(2)
  ["name"]=>
  string(9) "みかん"
}
// $stmt->setFetchMode(PDO::FETCH_INTO, $obj);
// 今回は適当なTest Classを作成した
object(Test)#3 (1) {
  ["cols":protected]=>
  array(2) {
    ["id"]=>
    int(1)
    ["name"]=>
    string(9) "りんご"
  }
}
object(Test)#3 (1) {
  ["cols":protected]=>
  array(2) {
    ["id"]=>
    int(2)
    ["name"]=>
    string(9) "みかん"
  }
}
// $stmt->setFetchMode(PDO::FETCH_ASSOC);
array(2) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(9) "りんご"
}
array(2) {
  ["id"]=>
  int(2)
  ["name"]=>
  string(9) "みかん"
}

デフォルト状態はなんとも使いづらい(なぜこれがデフォルト・・?)ので、いつもはPDO::FETCH_CLASSにして使っています。

参考:http://php.net/manual/ja/pdostatement.setfetchmode.php

10
7
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?