Reputation: 21518
I am trying to figure out how to fetch from PDO into my custom class, and in general the PDO-to-object API, and am finding the lack of decent documentation frustrating. Most of the options are only documented as an option, while the examples all use fetching into arrays.
So, can someone explain how these are used:
If possible, I would like a general explanation how each function/constant is used for fetching objects, or what the differences are, as well as a specific answer to how do I fetch into my class, e.g. into:
class MyRow {
public $col1, $col2;
}
Upvotes: 8
Views: 9355
Reputation: 21518
Here is what I managed to figure out:
PDO::FETCH_OBJ
Is used to fetch into a new instance of an unnamed ("anonymous") object
PDO::FETCH_CLASS
Is used to fetch into a new instance of an existing class (the column names should match existing properties, or __set
should be used to accept all properties). The constructor of the class will be called after the properties are set.
PDO::FETCH_CLASSTYPE
Used with FETCH_CLASS
(bitwise OR), the name of the class to create an instance of is in the first column, instead of supplied to the function.
PDO::FETCH_INTO
Is used with the same type of class as FETCH_CLASS
(must handle all columns as property names), but updates an existing object as opposed to creating a new one.
PDO::FETCH_LAZY
I don't know what this does.
PDOStatement::fetch
The regular get-a-row command. I don't know how to use this with FETCH_CLASS
or FETCH_INTO
since there does not be any way to pass the class name/instance.
PDOStatement::fetchObject
A way to do FETCH_CLASS
or FETCH_INTO
, including passing constructor args. With no args is a shorthand for FETCH_OBJ
.
PDOStatement::setFetchMode
A way to set the default fetch mode, so that PDOStatment::fetch
can be called without args.
That is the best I managed to figure out. I hope it helps someone else (I needed the fetchObject
method)
Upvotes: 11
Reputation: 346
After preparing a statement, use PDOStatement::setFetchMode with PDO::FETCH_CLASS:
$stmt = $pdo->query('SELECT col1, col2 FROM table');
$stmt->setFetchMode(\PDO::FETCH_CLASS, 'MyRow');
$obj = $stmt->fetch();
Upvotes: 1