Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP Designing Interfaces in PHP Introducing Interfaces Implement MySQL RepositoryInterface

Challenge Task 2 makes no sense. What is the name of the MySQL database table passed to the method?

  1. Define the "all" method to return all items from the MySQL database table passed to the method.
  2. Use "fetchAll(PDO::FETCH_OBJ)" to return the results as an array of objects.
sqlRepository.php
<?php

class sqlRepository extends PDO implements RepositoryInterface {
  public function all($entity){
    $db = new PDO("DS", "USERNAME", "PASSWORD");
    $query = $db->prepare("SELECT * FROM tablename");
    $query = $db->execute();
    $data = $db->fetchAll(PDO::FETCH_OBJ);
    return $data->$entity;
  }
}

2 Answers

Aymen Hachicha
Aymen Hachicha
12,653 Points

The Answer from Brad is not 100% correct. Our class extends PDO that means that our $this is a PDO-Object therefor could be used as $db variable itself. Here's what I mean:

<?php

class sqlRepository extends PDO implements RepositoryInterface 
{

    public function all($table) 
    {
        $db = $this;
        $query = $db->query("SELECT * FROM " . $table);
        $data = $query->fetchAll(PDO::FETCH_OBJ);
        return $data;
    }
}
?>
Brad Mullett
Brad Mullett
76,804 Points

Okay, here's the answer I got to work:

<?php

class sqlRepository extends PDO implements RepositoryInterface {

    public function all($entity){
        $db = new PDO("sqlite:".__DIR__."/database.db");
        $query = $db->query("SELECT * FROM ".$entity);
        $data = $query->fetchAll(PDO::FETCH_OBJ);
        return $data;
    }
}

?>

The challenge mentions that the table will be passed to the method, so $entity contains the table name.

The instructions for the challenge could have been a little more clear. I see you used parts from the integrating PHP with databases course. Thanks for the help Brad.

Thanks! I never would have gotten this. The $*&@# challenge stated that it wanted all records from a MySQL table.