How can I simply return objects in PDO?

后端 未结 4 1683
难免孤独
难免孤独 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 08:14

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

提交回复
热议问题