我有了下一个代码,他向用户展示了正在制作的新类别。问题是我不知道如何限制结果,并对最后5个类别进行类似的限制?谢谢抱歉英语不好。感谢
<?php
$stmt = $pdo->prepare('SELECT * FROM categories');
$stmt->execute();
echo $stmt->rowCount();
?>
</span>
</a>
<ul class="dropdown-menu extended notification">
<li>
<p>Categories</p>
</li>
<?php
if($stmt->rowCount() > 0) {
foreach($stmt->fetchAll() as $row) {
$html = '<li>';
$html .= '<div class="alert alert-info clearfix">';
$html .= '<span class="alert-icon"><i class="fa fa-flag"></i></span>';
$html .= '<div class="noti-info">';
$html .= 'Category #'.$row['CategoryID'].' '.$row['CategoryName'].'';
$html .= '</div>';
$html .= '</div>';
$html .= '</li>';
echo $html;
}
} else {
$html = '<li>';
$html .= '<div class="alert alert-danger clearfix">';
$html .= '<span class="alert-icon"><i class="fa fa-flag"></i></span>';
$html .= '<div class="noti-info">';
$html .= '<a href="#"> There are no available categories.</a>';
$html .= '</div>';
$html .= '</div>';
$html .= '</li>';
echo $html;
}
?>
在查询中使用ORDER BY、DESC和LIMIT,即:
SELECT * FROM categories ORDER BY ColumnNameEx DESC LIMIT 5;
ORDER BY
在某些情况下,
MySQL
可以使用索引来满足ORDER BY
子句而不需要进行额外的排序
即使ORDER BY
与精确索引,只要索引中所有未使用的部分额外的ORDER BY
列是WHERE
子句中的常量
http://dev.mysql.com/doc/refman/5.7/en/order-by-optimization.html
DESC
默认的排序顺序是升序,最小值优先。到按相反(降序)排序,在名称中添加
DESC
关键字您正在排序的列的。
http://dev.mysql.com/doc/refman/5.7/en/sorting-rows.html
LIMIT
如果只需要结果集中指定数量的行,请使用查询中的
LIMIT
子句,而不是获取整个结果集并丢弃多余的数据。
https://dev.mysql.com/doc/refman/5.5/en/limit-optimization.html
在查询"LIMIT x"的末尾添加,x是您想要获得的结果数量