How can I simply return objects in PDO?

pdo fetch object
pdo map to object
fetch_object in pdo
pdo->query
pdo fetchall
pdo fetch vs fetchall
pdo::fetch_class
php pdo

Trying out PDO for the first time.

$dbh = new PDO("mysql:host=$hostname;dbname=animals", $username, $password);

$stmt = $dbh->query("SELECT * FROM animals");
$stmt->setFetchMode(PDO::FETCH_INTO, new animals);

foreach($stmt as $animals)
{
    echo $animals->name;
}

If i skip the setFetchMode() method, then I need to call $animals["name"] which I do not want.

But I do not want to call the setFetchMode() for each query I do.

Is there a way to set the default FetchMode ? Or some other method to make the query() return objects with one global setting.

Perhaps you could try extending the PDO class to automatically call the function for you... in brief:

class myPDO extends PDO
{
   function animalQuery($sql)
   {
     $result = parent::query($sql);
     $result->setFetchMode(PDO::FETCH_INTO, new animals);
     return $result;
   }

//   // useful if you have different classes
//   function vegetableQuery($sql)
//   {
//     $result = parent::query($sql);
//     $result->setFetchMode(PDO::FETCH_INTO, new vegetables);
//     return $result;
//   }
}

$dbh = new myPDO("mysql:host=$hostname;dbname=animals", $username, $password);

$stmt = $dbh->animalQuery("SELECT * FROM animals");

foreach($stmt as $animals)
{
    echo $animals->name;
}

php - How can I simply return objects in PDO?, PECL pdo >= 0.2.4). PDOStatement::fetchObject — Fetches the next row and returns it as an object It just passes the result to the object. Output is like: In contrast, a PDO message can contain 8 full bytes of data - and it can contain multiple object parameter values within a single frame. Thus, what would require at least 4 frames with SDO could potentially be done with 1 frame in the PDO service. The PDO is often seen as the most important CANopen protocol as it carries the bulk of information.

Since PDO would need to know what object you want to fetch into, you would need to specify it manually. But of you just want to use the object to retrieve the data rather than an array and do not care if its not an animal object, you can use anonymous objects by default when you set the attribute after the connection string which could be done in a wrapped constructor

  $connection = new PDO($connection_string);
  //PDO::FETCH_OBJ: returns an anonymous object with property names that correspond to the column names returned in your result set 
  $connection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); 

Then all queries will return objects. Though it's not exactly what you want its close.


You could also inject the data into your animal class:

while($dataObj = ...) {
 $animal = new Animal($dataObj);
}

If you look at the query function it is possible to change some options by passing extra parameters: http://www.php.net/manual/en/pdo.query.php I haven't tested it but it looks like it gets you close to what you want

PDOStatement::fetchObject - Manual, PDOStatement::fetchAll — Returns an array containing all of the result set rows The fix is to simply specify your field names in the SELECT clause instead of� If you want to get a single object from the database, PDO is pretty helpful: $obj = $handle->fetchAll(PDO::FETCH_CLASS, $obj_name); If you expect multiple class types to be returned in a single row (e.g.: when doing JOINs), PDO is less helpful: $handle->fetchAll(PDO::FETCH_ASSOC);

Speaking of fetching objects in general, PDO has half a dozen different modes for this task. I had to write a dedicated article regarding fetching objects with PDO to list them all.

Regarding your particular questions,

How can I simply return objects in PDO?

Simply use the PDO::FETCH_OBJ mode

Is there a way to set the default FetchMode?

It depends. If your concern is just a syntax, and you simply want to use $animal->name instead of $animal['name'], then you can ask PDO to create instances of stdClass() by default. To do so, just add

PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ

to the list of your PDO connection options (the link is to another example I wrote, which I highly recommend to check out, because connection to PDO is a complex business that is anything but a single line from your example).

Having this option set you can have your object syntax right away:

$stmt = $dbh->query("SELECT * FROM animals");
foreach($stmt as $animal)
{
    echo $animal->name;
}

While in case you need to fetch into a particular class, for a list of objects either use your current approach with setFetchMode() / foreach or you can use fetchAll() with a dedicated PDO::FETCH_CLASS fetch mode:

$herd = $pdo->query('SELECT name FROM animals')->fetchAll(PDO::FETCH_CLASS, 'Animal');

This is all you can have, simply because you need to tell PDO, instances of which particular class you will need.

There are other options like providing constructor arguments and such. You can check them out in the article linked above.

PDOStatement::fetchAll - Manual, Getting a plain array. By default, this function will return just simple enumerated array consists of all the returned rows. Row formatting constants, such as PDO::� We connect to MySQL using the PDO object. In this particular example, I am using the database “test”. We create our SQL statement, which is “SHOW TABLES”. This SQL statement tells MySQL to return a list of the tables that exist in our currently-selected database. We prepare the SQL statement. We execute the SQL statement.

You can try this way:

$dbh = new PDO("mysql:host=$hostname;dbname=animals", $username, $password);

$stmt = $dbh->query("SELECT * FROM animals");
$stmt->setFetchMode(PDO::FETCH_CLASS, animals::class);

foreach($stmt as $animals)
{
    echo $animals->name;
}

Fetching objects with PDO, the getDb() method in the DbFactory Class, in using the way that the DbFactory class is instantiated (with the DI Bucket) that it can return just the PDO object? PDO and Dependency Injection Dependency injection is good for testing. But for anyone wanting various data mapper objects to have a database connection, dependency injection can make other model code very messy because database objects have to be instantiated all over the place and given to the data mapper objects.

(The only proper) PDO tutorial, PECL pdo >= 0.2.0). PDO::query — Executes an SQL statement, returning a result set as a PDOStatement object Return Values. PDO::query() returns a PDOStatement object, or FALSE on failure. object . It simply returns false. tgrl5000. PDO::lastInsertId— Returns the ID of the last inserted row or sequence value. PDO::prepare— Prepares a statement for execution and returns a statement object. PDO::query— Executes an SQL statement, returning a result set as a PDOStatement object. PDO::quote— Quotes a string for use in a query.

PDO returned as Object: Breaks Object Self State Management , PHP Data Objects (PDO) provides a clear, simple, unified API for working drivers ship with PHP as shared extensions, and simply need to be activated by Fetch method returns each row as an object with column names as� The Data Source Name, or DSN, contains the information required to connect to the database. In general, a DSN consists of the PDO driver name, followed by a colon, followed by the PDO driver-specific connection syntax. Further information is available from the PDO driver-specific documentation

PDO::query, Legal values include PDO::FETCH_ASSOC, PDO::FETCH_BOTH, Database:: RETURN_STATEMENT: Return the prepared statement object for the query. To suppress that behavior and simply return NULL on failure, set this option to� For this reason, I strongly recommend hydrating your objects manually, after retrieving the data as an array, rather than trying to have PDO apply properties directly to your objects. Clearly somebody thought they were being clever here - allowing you to access hydrated property-values from the constructor.