How can I simply return objects in PDO?

后端 未结 4 1681
难免孤独
难免孤独 2021-01-18 07:24

Trying out PDO for the first time.

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

$stmt = $dbh->query(\"SELECT * FROM ani         


        
4条回答
  •  悲&欢浪女
    2021-01-18 07:57

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

提交回复
热议问题