Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialHugo Zaanen
11,897 PointsUse 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.
<?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
Treehouse TeacherHi 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!
Hugo Zaanen
11,897 PointsHugo Zaanen
11,897 PointsYeah, 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