PHP Designing Interfaces in PHP Introducing Interfaces Implement MySQL RepositoryInterface

Hugo Zaanen
Hugo Zaanen
7,334 Points

Use pdo the execute sql query

I dont have a database connection yet, so i dont know what i have to do to make a PDO execute a sql query.

sqlRepository.php
<?php
class sqlRepository extends PDO implements RepositoryInterface
{
  public function all($items)
  {    
    $stmt = $dbh->prepare("SELECT * FROM " .$items);
    $stmt = execute();
    return $stmt->PDO->fetchAll(PDO::FETCH_OBJ);
  }
}

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there, Hugo Zaanen! Remember, this is a class. So very likely, at some point, you will make an instance of that class. You can refer to the instance, which inherits from PDO, as $this. You also are referencing PDO as if it is a method on PDO, but it isn't. And your middle line there should run the execute() method directly on the $stmt (which is an instance of PDO).

<?php
class sqlRepository extends PDO implements RepositoryInterface
{
  public function all($items)
  {    
    $stmt = $this->prepare("SELECT * FROM " .$items);  // prepare the PDO object with the SQL you want to run
    $stmt->execute();  // run the SQL on the PDO object
    return $stmt->fetchAll(PDO::FETCH_OBJ);  // get and return all the results returned by the execution of the SQL on the PDO
  }
}

Hope this helps! :sparkles:

Hugo Zaanen
Hugo Zaanen
7,334 Points

Yeah, thank you. This works apparently. I thought I already applied it. A friend of mine said that the execute has to contain the $items variabel as a array param. It already used your solution, but i really dont know anymore ;C