简体   繁体   English

PDO FETCH_CLASS意外行为

[英]PDO FETCH_CLASS unexpected behaviour

I am trying to return a new instance of my User class via a DAO, and am struggling to see if it is working, it certainly isn't working as I expected, as I am not defining User properties, yet I am still seeing all the User fields and values from the database. 我正在尝试通过DAO返回User类的新实例,并且正在努力查看它是否正在工作,因为我没有定义User属性,但是它确实没有按我预期的那样工作,但是我仍然看到了所有数据库中的用户字段和值。

class Database 类数据库

class Database
{   
    private $dbh;

    public function __construct()
    {
        $this->openConnection();
    }

    private function openConnection()
    {   
        try {
            $this->dbh = new PDO('mysql:host=localhost; dbname=stats', 'user', 'pass');
            $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $e) {
            'There was an error connecting to the database, error: ' . $e->getMessage();
        }
    }

    public function query($sql, $params)
    {   
        $stmt = $this->dbh->prepare($sql, $params);
        $stmt->execute($params);
        return $stmt;
    }
}

class UserDao 类UserDao

class UserDao
{   
    private $db;
    public function __construct($db) 
    {
        $this->db = $db;  

    }

    public function findById($ward_code)
    {   
        $record = $this->db->query("SELECT * from ward_statistics where WardCode = :WardCode", array(':WardCode' => $ward_code));
        $record->setFetchMode(PDO::FETCH_CLASS, 'User')
        $user = $record->fetch();
        return $user;       
    }
}

class User 类用户

class User 
{
    // with no properties defined, I still get a 
    // full result set from UserDAO::findById()

}

Usage 用法

$db = new Database();
$dao = new UserDao($db);
$user = $dao->findById('AMED');
var_dump($user);

Results in an object with a full result set from the DB (a single row that is - matched by the WardCode), with all fields populated with the correct values (from the DB). 从数据库中获得具有完整结果集的对象(与WardCode匹配的单行),并且所有字段都填充有正确的值(来自数据库)。

Whilst this seems OK - I thought that PDO::FETCH_CLASS required the properties to available within the class. 尽管这看起来还可以,但我认为PDO :: FETCH_CLASS要求该属性在该类中可用。

My worry is, from a question I posted on Code Review a few days ago, I was also told that class methods such as the findById one should create new class instances, or update the existing one, yet all I seem to be doing is retrieving a row from the database. 我担心的是,根据几天前我在Code Review上发布的一个问题 ,我还被告知,诸如findById之类的类方法应该创建新的类实例,或者更新现有的类实例,但是我似乎要做的只是检索数据库中的一行。

Thanks 谢谢

Replace fetchAll with fetch if you need just 1 object. 如果只需要1个对象,则将fetchAll替换为fetch According to documentation : 根据文件

PDOStatement::fetchAll — Returns an array containing all of the result set rows PDOStatement :: fetchAll —返回包含所有结果集行的数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM