查询返回1太多行

时间:2012-03-13 02:52:14

标签: php pdo

 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()是否合适?

1 个答案:

答案 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();