0

我正在尝试使用 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 中编程,所以我的理解仍然模糊。

4

2 回答 2

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'];    
}
于 2013-11-03T15:01:03.657 回答
1

$statement 变量是 CommentFactory 类的实例,因此它没有 fetch 方法,这就是您收到错误的原因。

您可以将 STMT 对象分配给一个变量并循环遍历该变量,例如

$stmt = $statement->getImage();
while($id = $stmt->fetch(PDO::FETCH_ASSOC))

但我不建议你这样做。

首先,将数据库连接注入对象方法对我来说感觉不对,您可以在创建 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

于 2013-11-03T15:09:54.353 回答