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; }