This question already has an answer here:
I am trying to retrieve my database rows using OOP I keep getting an error though. I feel like I am missing something simple to make this work. My code is below:
Class CommentFactory {
public function getImage(PDO $conn){
$stmt2 = $conn->prepare('SELECT * FROM `pictures`');
$stmt2->execute();
return $stmt2;
}
}
$statement = new CommentFactory();
$statement->getImage($conn);
while ($idOfComment = $statement->fetch(PDO::FETCH_ASSOC)) {
echo $idOfComment['photo_id'];
}
The error I am getting is:
Fatal error: Call to undefined method CommentFactory::fetch() in /var/www/CommentSystem/includes/Classes.php on line 29
I just recently began trying to program in OOP so my understanding is still vague.
</div>
You are only returning a value from the method getImage()
, therefore you should do:
Class CommentFactory {
protected $conn;
public function getImage($conn){
$stmt2 = $conn->prepare('SELECT * FROM `pictures`');
$stmt2->execute();
return $stmt2;
}
}
$statement = new CommentFactory();
$values = $statement->getImage($conn);
while ($idOfComment = $values->fetch(PDO::FETCH_ASSOC)){
echo $idOfComment['photo_id'];
}
Edit: However, as engvrdr noted, this is not the best you can do. You could the method to return the array, furthermore, you can pass the connection in the constructor as shown here:
Class CommentFactory {
protected $conn;
public function __construct($conn) {
$this->con = $conn;
}
public function getImage(){
$stmt2 = $this->conn->prepare('SELECT * FROM `pictures`');
$stmt2->execute();
return $values->fetchAll(PDO::FETCH_ASSOC);
}
}
$statement = new CommentFactory($conn);
foreach ($statement->getImage() as $Image){
echo $Image['photo_id'];
}
$statement variable is a instance of a CommentFactory class so it doesn't have a fetch method, that's why you are getting error.
you can either assign STMT object to a variable and loop through that variable like
$stmt = $statement->getImage();
while($id = $stmt->fetch(PDO::FETCH_ASSOC))
But i don't advise you to do it.
First of all, injecting db connection to a object method doesn't feel right to me, you can inject the connection object while you are creating CommentFactory object like;
class CommentFactory{
private $conn;
public $images;
public function __construct($connection){
$this->conn = $connection;
}
public function getImage(){
$stmt2 = $this->conn->prepare('SELECT * FROM `pictures`');
$stmt2->execute();
while ($idOfComment = $stmt2->fetch(PDO::FETCH_ASSOC)){
$this->images[] = $idOfComment['photo_id'];
}
}
}
$statement = new CommentFactory($conn);
$statement->getImage();
foreach($statement->images as $photo_id)
echo $photo_id;
}
by the way, if you mean Factory design pattern by naming like CommentFactory,i advise you to have a look at example at wikipedia (http://en.wikipedia.org/wiki/Factory_method_pattern#PHP)