我正在尝试使用OOP检索我的数据库行但是我仍然遇到错误。我觉得我错过了一些简单的工作。我的代码如下:
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'];
}
我得到的错误是:
Fatal error: Call to undefined method CommentFactory::fetch() in /var/www/CommentSystem/includes/Classes.php on line 29
我刚刚开始尝试在OOP中编程,所以我的理解仍然模糊不清。
答案 0 :(得分:1)
您只是从方法getImage()
返回一个值,因此您应该这样做:
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'];
}
编辑:但是,正如 engvrdr 所指出的那样,这不是你能做的最好的事情。您可以使用该方法返回数组,此外,您可以在构造函数中传递连接,如下所示:
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'];
}
答案 1 :(得分:1)
$ statement变量是CommentFactory类的一个实例,因此它没有fetch方法,这就是你收到错误的原因。
您可以将STMT对象分配给变量并循环遍历该变量,如
$stmt = $statement->getImage();
while($id = $stmt->fetch(PDO::FETCH_ASSOC))
但我建议你不要这样做。
首先,将db连接注入对象方法对我来说感觉不对,您可以在创建CommentFactory对象时注入连接对象;
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;
}
顺便说一下,如果你的意思是像CommentFactory那样命名工厂设计模式,我建议你看看维基百科的例子(http://en.wikipedia.org/wiki/Factory_method_pattern#PHP)