使用带有LIMIT的ORDER BY的PHP / MySQL

时间:2013-02-05 12:12:17

标签: php mysql pagination

我大致通过以下链接创建了一个分页:

http://www.awcore.com/dev/1/3/Create-Awesome-PHPMYSQL-Pagination_en#toggle

很酷。虽然我的查询有问题。

它的工作原理如下:

require 'includes/function.php';

    $page = (int) (!isset($_GET["page"]) ? 1 : $_GET["page"]);
    $limit = 8;
    $startpoint = ($page * $limit) - $limit;

    $statement = "cars WHERE deleted = 'no'";

$query = mysql_query("SELECT * FROM {$statement} LIMIT {$startpoint}, {$limit} ");

while ($row = mysql_fetch_assoc($query)) {

但是,当我尝试向此添加ORDER BY时,如下所示:

要求'includes / function.php';

    $page = (int) (!isset($_GET["page"]) ? 1 : $_GET["page"]);
    $limit = 8;
    $startpoint = ($page * $limit) - $limit;

    $statement = "cars WHERE deleted = 'no'";

$query = mysql_query("SELECT * FROM {$statement} LIMIT {$startpoint}, {$limit} ORDER BY model DESC");

while ($row = mysql_fetch_assoc($query)) {

或者只是改变这样的语句:

$statement = "rcr_cars WHERE deleted = 'no' ORDER BY model DESC";

我收到此错误:

Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in filepath/myfile.php on line 79.

第79行是这一行:

 while ($row = mysql_fetch_assoc($query)) {

任何人都可以告诉我我没有正确使用ORDER BY,它让我感到困惑。 :/

3 个答案:

答案 0 :(得分:3)

尝试以下查询

$query = mysql_query("SELECT * FROM {$statement} ORDER BY model DESC LIMIT {$startpoint}, {$limit} ");

你出错的地方是LIMIT应该在ORDER BY之后。 Read more

答案 1 :(得分:0)

更改查询:

$query = mysql_query("SELECT * FROM {$statement} ORDER BY model DESC LIMIT {$startpoint}, {$limit}") ;

答案 2 :(得分:0)

$query = mysql_query("SELECT * FROM {$statement} ORDER BY model DESC LIMIT {$startpoint}, {$limit} ");