分页时出现语法错误

时间:2013-01-02 01:14:46

标签: php mysql pagination

这应该是一个相当直接的问题。我收到Warning: mysql_num_rows() expects parameter 1 to be resource, boolean错误,我无法弄清楚正确的语法。使用mysqlerror我得到You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-5, 5'

任何帮助都会很棒。代码是我添加的分页的一部分。

受影响代码的片段

<?php
//Number of items to display per page  
$perpage = 5;

if(isset($_GET["page"]))
{
    $page = intval($_GET["page"]);
}
else
{
    $page = 1;
}

$calc = $perpage * $page;
$start = $calc - $perpage;
$result = mysql_query("select * from products Limit $start, $perpage");
$rows = mysql_num_rows($result);
echo mysql_error();

if($rows)
{
    $i = 0;
    while($post = mysql_fetch_array($result))
{
?>

2 个答案:

答案 0 :(得分:2)

$ start不能为负(而且是)。你应该确保$ page不小于1.这应该可以解决你的问题:

<?php
 //Number of items to display per page  
 $perpage = 5;
 $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
 if ($page < 1)
 {
   $page = 1;
 }
 $calc = $perpage * $page;
 $start = $calc - $perpage;
 $result = mysql_query("select * from products Limit $start, $perpage");
 $rows = mysql_num_rows($result);
 echo mysql_error();
 if($rows)
 {
  $i = 0;
  while($post = mysql_fetch_array($result))
  {
?>

答案 1 :(得分:2)

当您使用LIMIT时,起点的值应大于或等于零。