简体   繁体   中英

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.

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

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).

Whilst this seems OK - I thought that PDO::FETCH_CLASS required the properties to available within the 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.

Thanks

Replace fetchAll with fetch if you need just 1 object. According to documentation :

PDOStatement::fetchAll — Returns an array containing all of the result set rows

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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