检索数据库表信息 OOP


Retrieving database table info OOP

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

你只从方法返回一个值 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'];    
}

$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)的示例