tags:

views:

319

answers:

1

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.

+2  A: 

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;
}
Martin
I had this in mind but wanted to look for something built in :) Thanks though. +1
Ólafur Waage
Accepting this since this is what i need to do.
Ólafur Waage