我有一个名为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循环只出现一行。此外,我试图使循环在我的类文件,但它没有工作。
请帮助。
这只获取一行:
$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
}