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 trialJohn Shockey
45,061 PointsChallenge Task 2 makes no sense. What is the name of the MySQL database table passed to the method?
- Define the "all" method to return all items from the MySQL database table passed to the method.
- Use "fetchAll(PDO::FETCH_OBJ)" to return the results as an array of objects.
<?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
12,653 PointsThe 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
76,854 PointsOkay, 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.
John Shockey
45,061 PointsThe 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
6,339 PointsThanks! I never would have gotten this. The $*&@# challenge stated that it wanted all records from a MySQL table.