1

want from a method return an array of objects, what is the best way retrieving data from the db and then populate a list of objects to be returned.

       <?php

        class DataObject{
          public function GetObjetList(){
           // Connect to the database server
           $dbh = new PDO("mysql:host=localhost;dbname=bookdb", "webuser", "secret");
           // Execute the query return 1200 register
           $stmt = $dbh->query('SELECT sku, title FROM products ORDER BY title');
           while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $sku = $row['sku'];
                $title = $row['title'];
                return something?? --> how to??
          }
        }
       ?>

regards!

3 Answers 3

2

PDO already has a fetch mode that returns objects.

Change your code to this:

while ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
Sign up to request clarification or add additional context in comments.

Comments

-1
class DataObject
{
    public function __construct($pdo)
    {
        $this->db = $pdo;
    }
    public function GetObjetList()
    {
        $sql = 'SELECT sku, title FROM products ORDER BY title';
        return $this->db->query($sql)->fetchAll(PDO::FETCH_OBJ);
    }
}

Comments

-2

Put the return after the while, not inside, use FETCH_OBJ and an array:

     $rows = array();
     $rows = $stmt->fetchAll(PDO::FETCH_OBJ);
     return $rows;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.