class getPosts
{
public $post_id;
public $title;
public $content;
public $author;
function __construct($inPost_id=null, $inTitle=null, $inContent=null, $inAuthor=null)
{
$this->post_id = $inPost_id;
$this->title = $inTitle;
$this->content = $inContent;
$this->author = $inAuthor;
}
function getPosts()
{
$postnumber = 14;
$query = $dbh->prepare("SELECT * FROM posts ORDER BY ID DESC LIMIT $postnumber");
$query->execute();
$postArray = array();
while ($row = $query->fetch())
{
$myPost = new getPosts($row["id"],
$row['title'], $row['content'],
$row['author'], $row["author_id"]);
array_push($postArray, $myPost);
}
return $postArray;
}
}
这是有效但不太好,而不是14,它返回15。
在PDO::FETCH_ASSOC
中使用fetch()
是否合适?
答案 0 :(得分:1)
使用预准备语句时,您应该绑定任何参数:
$postnumber = 14;
$query = $dbh->prepare("SELECT * FROM posts ORDER BY ID DESC LIMIT :postnumber");
$query->bindParam(':postnumber', $postnumber, PDO::PARAM_INT);
$query->execute();