Search code examples
phppdokohana

PDO FetchAll Fetch_Class not returning all rows/objects


When using PDO::FetchAll() in association with PDO::Fetch_Class i don't get all objects back. Just one object out of 5 or 6.

example:

$as_object = 'Model_Menu'; $params = NULL;

$result->setFetchMode(PDO::FETCH_CLASS, $as_object, $params);

$result = $result->fetchAll();

But using $result->setFetchMode(PDO::FETCH_ASSOC); gives me all the rows in the database.

Im using Kohana so i cant really show you the whole build of the query itself. But trust me it works, if fetch assoc does get all the result with the same build it should work right?

Environment :

-Linux ubuntu
-Driver: pdo/mssql/?ORM?
-Framework: Kohana

Solution

  • Perhaps, because you're passing a third argument ($params, which is null), PDO assumes the fetchmode to be PDO::FETCH_CLASS | PDO::FETCH_INTO, re-assigning $params over and over. Remember that PDO::FETCH_CLASS will not call the constructor until after all properties are set. To call the constructor first, you need to set the fetch mode to PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE. Id' git this a bash:

    $result->setFetchMode(
        PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE,
        $asObject
    );
    $objects = $result->fetchAll();
    

    Looking at the docs, I've also noticed that most examples look like this:

    $stmt->execute(); //<-- execute
    $rows = $stmt->fetchAll(PDO::FETCH_CLASS, 'ClassName');//pass fethcMode upon fetching