PDO :: FETCH_CLASSTYPE - 意外结果

时间:2012-03-03 23:31:32

标签: php pdo pdostatement

我在这里失败了。不知道为什么我得到“stdClass”。我不应该从第一栏获得名字吗?

$sql = "SELECT cn, iso2, iso3, fid, sort FROM ct";
$stmt = $dbh->query($sql);
$result = $stmt->fetch( PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE );
var_dump($result);

//expected - first: cn.col holds country names
object(Brazil)[3]
  public 'iso2' => string 'BR' (length=2)
  public 'iso3' => string 'BRA' (length=3)
  public 'fid' => string '1' (length=1)
  public 'sort' => string '0' (length=1)

//received
object(stdClass)[3]
  public 'iso2' => string 'BR' (length=2)
  public 'iso3' => string 'BRA' (length=3)
  public 'fid' => string '1' (length=1)
  public 'sort' => string '0' (length=1)var_dump

1 个答案:

答案 0 :(得分:0)

问题很可能是未定义类(或范围内)。我使用本地数据进行了一些测试。

$conn = new PDO("mysql:host=localhost;dbname=test", 'user', 'pass');
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING ); 

$stmt = $conn->prepare("SELECT name,email FROM `test_table`");
$stmt->execute();
$result = $stmt->fetch( PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE );

print_r($result) // returns stdClass Object ( [email] => 'test@test.com' ) 

通过在PDO代码上方添加以上内容

Class levi{

}

我能够让它返回:

levi Object ( [email] => 'test@test.com')