PHP MySQLi Pagination


PHP MySQLi Pagination

我正在尝试构建一个分页应用程序,但我的代码一直失败,我不知道为什么。当我在查询中用数字而不是变量替换 LIMIT 变量时,它有效。

$pageNum = $_GET['page'];
    $id = $_GET['id'];
if ($pageNum == NULL) {
$pageNum = 1;   
}
include("config.php");
include("header.php");
$numPosts = $connect->query("SELECT * FROM forum_posts WHERE category='" . $id . "'         ORDER BY latestReply ASC");
$numPosts = $numPost->num_rows;
$resultsPerPage = 10;
$lastPage = ceil($numPosts/$resultsPerPage);
if (!(isset($pagenum))){ 
 $pageNum = 1; 
 }
 if ($pagenum < 1) { 
 $pageNum = 1; 
 } elseif ($pageNum > $lastPage) { 
 $pageNum = $lastPage; 
 } 
$limit1 = $pageNum * $resultsPerPage - $resultsPerPage;
$limit2 = $limit1 + $resultsPerPage;
$post = $connect->query("SELECT * FROM forum_posts LIMIT $limt1, $limit2 WHERE category='" . $id . "' ORDER BY latestReply ASC");

但是,我不断收到此错误:

[17-Nov-2013 17:12:22 Europe/London] PHP Warning:  mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in /home/robbiewi/public_html/forum/category.php on line 59

在这一行上:

while ($posts = mysqli_fetch_array($post)) {

非常感谢所有的帮助!

WHERE条件应放在LIMIT之前

应该是

SELECT * FROM forum_posts WHERE category='" . $id . "' ORDER BY latestReply ASC LIMIT $limt1, $limit2

而不是

SELECT * FROM forum_posts LIMIT $limt1, $limit2 WHERE category='" . $id . "' ORDER BY latestReply ASC

选择语法:http://dev.mysql.com/doc/refman/5.0/en/select.html

SELECT
[ALL | DISTINCT | DISTINCTROW ]
  [HIGH_PRIORITY]
  [STRAIGHT_JOIN]
  [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
  [SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
select_expr [, select_expr ...]
[FROM table_references
[WHERE where_condition]
[GROUP BY {col_name | expr | position}
  [ASC | DESC], ... [WITH ROLLUP]]
[HAVING where_condition]
[ORDER BY {col_name | expr | position}
  [ASC | DESC], ...]
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
[PROCEDURE procedure_name(argument_list)]
[INTO OUTFILE 'file_name' export_options
  | INTO DUMPFILE 'file_name'
  | INTO var_name [, var_name]]
[FOR UPDATE | LOCK IN SHARE MODE]]
  1. 您在 SQL 语句中写了 $limt 1,但我想您现在只是打错了。
  2. 您确定 $limit 1 和 $limit 2 是数字吗?也许你可以在使用$limit1 = $limit1 * 1时修复它以确保它是数字,有时对我有用。