PDO准备语句限制不起作用[重复]
问题描述:
This question already has an answer here:
I'm attempting to limit the amount of results returned from an SQL query, but for some reason it's returning NULL. If I remove the LIMIT, all works fine. I've tested the query in Sequel Pro and it also works fine with the LIMIT. Am I doing something wrong here?
public static function getMostViewedPictures($limit = 5) {
$dbh = self::connectToDatabase();
$sql = "SELECT
picture.`title`,
picture.`description`,
picture.`slug`,
picture.`image`,
picture.`timestamp`,
picture.`views`,
category.category as category
FROM picture
LEFT JOIN category
ON picture.category_id = category.id
ORDER BY picture.views ASC
LIMIT 0, :limit";
$sth = $dbh->prepare($sql);
$sth->execute(array(':limit' => $limit));
if($results = $sth->fetchAll(PDO::FETCH_OBJ)) {
$pictures = array();
foreach($results as $result) {
$pictures[] = new Picture(
$result->title,
$result->description,
$result->slug,
$result->timestamp,
$result->category,
$result->views,
$result->image
);
}
return $pictures;
} else {
return null;
}
}
</div>
此问题已经存在 这里有一个答案: p>
-
如何在LIMIT子句中应用bindValue方法?
10 answers
span>
li>
ul>
div>
我试图限制从SQL查询返回的结果数量 ,但由于某种原因,它返回NULL。 如果我删除LIMIT,一切正常。 我在Sequel Pro中测试了这个查询,它也适用于LIMIT。 我在这里做错了吗? p>
public static function getMostViewedPictures($ limit = 5){ $ dbh = self :: connectToDatabase(); $ sql =“SELECT 图片.title`, 图片。描述`, 图片.slug`, 图片.image`, 图片.timestamp`, 图片.view` , category.category as category FROM picture LEFT JOIN category ON picture.category_id = category.id ORDER BY picture.views ASC LIMIT 0,:limit“; $ sth = $ dbh-&gt; prepare($ sql); $ sth-&gt; execute(array(':limit'=&gt; $ limit)); if($ results = $ sth-&gt; fetchAll (PDO :: FETCH_OBJ)){ $ pictures = array(); foreach($ results as $ result){ $ pictures [] = new Picture( $ result-&gt; title,\ n $ result-&gt; description, $ result-&gt; slug, $ result-&gt; timestamp, $ result-&gt; category, $ result-&gt; views, $ result-&gt; image ); } 返回$ pictures; } else { return null; } } code> pre> div>
答
Solved.
$sth->bindParam(':limit', $limit, PDO::PARAM_INT);