I am having a weird issue with PDO when I query a DB2 database using ODBC. I am using PHP 5.3.8 compiled using DB2 Express-C V9.7. The result set always returns dual values for each开发者_如何学JAVA column. Here's the code:
$pdo = new PDO("odbc:DRIVER={IBM DB2 ODBC DRIVER};DATABASE=xxxx; HOSTNAME=x.y.z.a;PORT=xxxxx;CurrentSchema=xxx;", "username", "password");
$sql = 'select * from cust_div where cust_no = '.$params.';';
$stmt = $pdo->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
$stmt->closeCursor();
var_dump($result)
always returns dual values:
array(1) {
[0]=>
array(52) {
["CUST_NO"]=>
string(9) "226622249"
[0]=>
string(9) "226622249"
["DIV_ID"]=>
string(1) "P"
[1]=>
string(1) "P"
etc.
What am I doing wrong here?
This is defined behavior for PDO. The array (for each row) returned by fetch()
or fetchAll()
contains data indexed by column name and order in the table.
If you don't want the numerically indexed results you can add the PDO::FETCH_ASSOC
constant to your call to fetch:
$stmt->fetch(PDO::FETCH_ASSOC); //Just column names and values
//OR
$stmt->fetchAll(PDO::FETCH_ASSOC);
The default value for this first parameter (which PHP.net calls fetch style) is PDO::FETCH_BOTH
which returns both PDO::FETCH_ASSOC
and PDO::FETCH_NUM
. More can be found on these return styles on the fetch() doc page.
For the table below and the query SELECT * FROM cust
:
+--+----+
|id|name|
+--+----+
|0 |John|
+--+----+
|1 |Jill|
+--+----+
Calling $stmt->fetchAll(PDO::FETCH_ASSOC);
would return:
array(0=>array(
'id' => 0,
'name' => 'John'
), 1=>array(
'id' => 1,
'name' => 'Jill'
));
While calling $stmt->fetch(PDO::FETCH_NUM);
would return:
array(0=>array(
0 => 0,
1 => 'John'
), 1=>array(
0 => 1,
1 => 'Jill'
));
The default (PDO::FETCH_BOTH
), which is what you've encountered, returns a combination of both of them. Since it is the default, it is used when no style is passed:
$stmt->fetch();
Or when it is explicitly provided:
$stmt->fetch(PDO::FETCH_BOTH);
You can define the "fetch style" by passing in an argument to fetchall()
.
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
See here: http://www.php.net/manual/en/pdostatement.fetch.php
精彩评论