Help us understand the problem. What is going on with this article?

PDOのfetchModeを比較してみた

More than 3 years have passed since last update.

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

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away