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

Hugo Zaanen
Hugo Zaanen
11,851 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
11,851 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