循环通过类方法OOP + PDO

时间:2015-10-22 06:53:30

标签: php oop pdo

我有一个名为POSTS的课程,这里是代码:

<?php
// This is a class file:
        class POSTS {
            private $connection;
            public $title;
            public $details;

            // This connection coming from another PDO file.
            function __construct($dbConn) {
                $this->connection = $dbConn;
            }

            public function getRealtedPosts($section_name) {
                $stm = $this->connection->prepare("SELECT * FROM posts WHERE section_name !=:Section_name");
                $stm->bindParam(":Section_name", $section_name);
                $stm->execute();

                $results = $stm->fetch(PDO::FETCH_OBJ);
                $this->title = $results->title;
                $this->details = $results->details;
            }
        }

        // Here the Index File:
        // I already Initiated the class and connection by
        // required the PDO file.

        $section_name = 'PHP';

        while ($POSTS->getRealtedPosts($section_name)) {
            $post_title = $POSTS->title;
            $post_details = $POSTS->details;
        ?>
            <div class="post">
                <h1><?php echo $post_title;?></h1>
                <p><?php echo $post_details;?></p>
            </div>
        <?php
        }
?>

不幸的是输出没什么:(但是如果我删除了while循环,则只出现一行。 此外,我试图在我的类文件中创建循环,但它不起作用。

请帮助。

1 个答案:

答案 0 :(得分:1)

这只取一行:

$results = $stm->fetch(PDO::FETCH_OBJ);

只需将其替换为:

$results = $stm->fetchAll(PDO::FETCH_OBJ);

当然,您需要将所有结果存储在某处,目前您只存储班级中一行的标题和详细信息。

一个完整的例子:

class POSTS {

   // the rest of your class

   public function getRealtedPosts( $section_name ) {
        $stm = $this->connection->prepare("SELECT * FROM posts WHERE section_name !=:Section_name");
        $stm->bindParam(":Section_name", $section_name);
        $stm->execute();

        return $stm->fetchAll( PDO::FETCH_OBJ );
    }
}

然后,在索引文件中:

$results = $POSTS->getRealtedPosts( $section_name );
foreach ( $results as $post ) {
?>
    <div class="post">
        <h1><?php echo $post->title;?></h1>
        <p><?php echo $post->details;?></p>
    </div>
<?php
}