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:
- PDO::FETCH_OBJ
- PDO::FETCH_CLASS
- PDO::FETCH_CLASSTYPE
- PDO::FETCH_INTO
- PDO::FETCH_LAZY
- PDOStatement::fetch
- PDOStatement::fetchObject
- PDOStatement::setFetchMode
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;
}
Here is what I managed to figure out:
Constants
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
__setshould 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.
Functions
PDOStatement::fetch
The regular get-a-row command. I don’t know how to use this with
FETCH_CLASSorFETCH_INTOsince there does not be any way to pass the class name/instance.PDOStatement::fetchObject
A way to do
FETCH_CLASSorFETCH_INTO, including passing constructor args. With no args is a shorthand forFETCH_OBJ.PDOStatement::setFetchMode
A way to set the default fetch mode, so that
PDOStatment::fetchcan be called without args.That is the best I managed to figure out. I hope it helps someone else (I needed the
fetchObjectmethod)