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,652 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,474 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.

Eric Drake
Eric Drake
Pro Student 6,225 Points

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