使用FETCH_CLASS进行PDO获取返回false

时间:2016-05-05 14:55:50

标签: php class pdo fetch

我在User.php中有一个简单的课程:

class User {
    private $id;
    private $username;
    private $password;
    private $email;
    private $first_name;
    private $last_name;
    private $active;
    // Getters and setters generated by NetBeans...
}

我的数据库表名为users

`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL,
`email` varchar(100) NOT NULL,
`first_name` varchar(100) DEFAULT NULL,
`last_name` varchar(100) DEFAULT NULL,
`active` int(10) unsigned DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`),
UNIQUE KEY `username_UNIQUE` (`username`),
UNIQUE KEY `email_UNIQUE` (`email`)

我的UserDAO.php文件的一部分:

...
require_once './db/DBConn.php';
require_once './user/User.php';
...
public static function getById($id) {
    try {
        $db = DBConn::getInstance();
        $query = "SELECT * FROM users WHERE id=:id";
        $stmt = $db->getConn()->prepare($query);
        $stmt->execute(array('id' => $id));
        $user = $stmt->fetch(PDO::FETCH_CLASS, "User");
        var_dump($user);
        return $user;
    } catch (PDOException $e) {
        echo "<br/>ERROR: User fetching by ID failed!<br/>";
        return 0;
    }
}
...

所以,当我打电话时,让我们说getById(1)(或任何其他有效参数),该函数执行所有内容,然后执行var_dump($user)输出bool(false)

如果我只放fetch()代替fetch(PDO::FETCH_CLASS, "User")var_dump将提供以下内容:

array(14) {
  ["id"]=>
  string(2) "1"
  [0]=>
  string(2) "1"
  ["username"]=>
  string(4) "abcd"
  [1]=>
  string(4) "abcd"
  ["password"]=>
  string(60) "$2y$10$wTCajtRU1xXf6Z65dZYjk.mx3tClFLujshS49SvYIuGW/lDZSH3nK"
  [2]=>
  string(60) "$2y$10$wTCajtRU1xXf6Z65dZYjk.mx3tClFLujshS49SvYIuGW/lDZSH3nK"
  ["email"]=>
  string(13) "test@test.com"
  [3]=>
  string(13) "test@test.com"
  ["first_name"]=>
  string(7) "John"
  [4]=>
  string(7) "John"
  ["last_name"]=>
  string(13) "Johnson"
  [5]=>
  string(13) "Johnson"
  ["active"]=>
  string(1) "0"
  [6]=>
  string(1) "0"
}

我也试过fetch(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE,"User")。什么都没有改变。

我做错了什么?为什么我无法使用User创建fetch类实例?

感谢。

1 个答案:

答案 0 :(得分:1)

您不能将PDO::FETCH_CLASS与fetch一起使用。您必须事先进行setFetchMode()来电:

public static function getById($id) {
    $db = DBConn::getInstance();
    $query = "SELECT * FROM users WHERE id=:id";
    $stmt = $db->getConn()->prepare($query);
    $stmt->execute(array('id' => $id));
    $stmt->setFetchMode( PDO::FETCH_CLASS, 'User');
    return $stmt->fetch();
}

此外,请注意,您永远不应该捕获错误异常以报告它们。它会使您的代码变脏,无法维护且不安全。