dpk20361
2019-06-11 16:38 阅读 83
已采纳

在php中循环通过类对象?

I can figure out how to loop through a table from the database now that I converted to class it.

Old code

<?php
$sql = "WHERE * FROM Somewere";
$result = $pdo->query($sql);
$products = $result->fetchAll(PDO::FETCH_ASSOC);
?>

<?php foreach ($products as $product) ?>

New code

<?php
class Posts extends Database
{
    public function postsToPost()
    {

        $stmt = $this->connect()->prepare("WHERE * FROM Somewere");
        $stmt->execute();

        $products = $stmt->fetchAll(PDO::FETCH_ASSOC);

    }

}
?>

<?php foreach ($products as $product) ?>

Do I need now loop inside the class and then output in my page? I'm confused. Thanks

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    doouzlrvb01417498 doouzlrvb01417498 2019-06-11 17:21

    You can return the result:

    class Posts extends Database
    {
        public function postsToPost()
        {
    
            $stmt = $this->connect()->prepare("WHERE * FROM Somewere");
            $stmt->execute();
    
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
    
        }
    
    }
    

    and then instantiate Posts, like this:

    $posts = new Posts();
    $products = $posts->postsToPost();
    foreach ($products as $product);
    
    点赞 评论 复制链接分享

相关推荐