user1941674
user1941674

Reputation: 43

Syntax error on pagination

This should be a fairly straight forward question. I am getting a Warning: mysql_num_rows() expects parameter 1 to be resource, boolean error and I can't figure out the correct syntax. Using mysqlerror I am getting 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' .

Any help would be great. The code is part of a pagination that I am adding.

Snippet of affected code

<?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))
{
?>

Upvotes: 0

Views: 137

Answers (2)

Wojciech Zylinski
Wojciech Zylinski

Reputation: 2035

$start cannot be negative (and it is). You should make sure, that $page is not less than 1. This should fix your problem:

<?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))
  {
?>

Upvotes: 2

John Woo
John Woo

Reputation: 263723

when you're using LIMIT the value of the starting point should be greater or equal to zero.

Upvotes: 2

Related Questions