【发布时间】:2016-01-19 21:41:08
【问题描述】:
我在一个单独的文件中有一个名为帖子的类:
<?php
class POSTS {
//Start of class properties:
private $db_connection;
public $post_id;
public $section_id;
public $user_id;
public $post_title;
public $post_details;
public $post_date;
public $post_category;
public $post_display;
public $num_of_rows;
public function getRelatedPosts($section_name, $category, $display) {
$stm = $this->db_connection->prepare("SELECT * FROM posts WHERE section_name!=:Section_name AND category=:Category AND display=:Display ORDER BY id DESC");
$stm->bindParam(":Section_name", $section_name);
$stm->bindParam(":Category", $category);
$stm->bindParam(":Display", $display);
$stm->execute();
$this->num_of_rows = $stm->rowCount();
if ($this->num_of_rows >= 1) {
$post_data = $stm->fetch(PDO::FETCH_OBJ);
$this->post_id = $post_data->id;
$this->section_id = $post_data->section_id;
$this->user_id = $post_data->user_id;
$this->post_title = $post_data->title;
$this->post_details = $post_data->details;
$this->post_date = $post_data->date;
$this->post_category = $post_data->category;
$this->post_display = $post_data->display;
}
}
}
?>
然后我想遍历我的索引文件中的结果:
$section_name = 'PHP';
$display = 'yes';
$POSTS->getRelatedPosts($section_name, $category $display);
$num_of_rows = $POSTS->num_of_rows;
if ($num_of_rows >= 1) {
for ($m=1; $m<=$num_of_rows; $m++) {
$post_id = $POSTS->post_id;
$section_id = $POSTS->section_id;
$user_id = $POSTS->user_id;
$post_title = $POSTS->post_title;
$post_details = $POSTS->post_details;
$post_date = $POSTS->post_date;
?>
<div id="related_post">
<h4><a href=""><?php echo $post_title;?></a></h4>
<p><?php echo $post_details;?></p>
</div>
<?php
}
} else {
echo 'Sorry no related posts now!';
}
不幸的是,结果只有一条记录重复了与 $num_of_rows 变量相等的次数。 我尝试了一些不同的获取方法,例如: fetchAll() 和其他样式,但结果总是错误或仅重复一条记录。
请有人帮我写代码。
【问题讨论】:
-
可能不是问题,但正如 PHP 手册中所述,
rowCount()就像您在$stm->rowCount()中所看到的那样,在SELECT语句中可能不准确。你会想要做一个COUNT()。 (示例 #2:php.net/manual/en/pdostatement.rowcount.php) -
另外,您有一个
getRelatedPosts()方法,但您在脚本中使用了getSectionPosts()?getRelatedPosts()怎么了? -
rowCount() 函数在这个例子中可以正常工作,感谢您的建议。
-
^ 正如我所说,建议不要将其用于
SELECT,我只是让您知道,以防您不知道。