How can I simply return objects in PDO?

后端 未结 4 1679
难免孤独
难免孤独 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:06

    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.

提交回复
热议问题