I'm executing a SQL Statement in PHP, using LIMIT $start, $offset
to paginate results.
An unexpected hurdle, is $stmt->num_rows
is returning all rows regardless of SQL LIMIT
. Here is my code, just incase I haven't made a silly mistake:
$term = '%'.$search.'%'; // I have used htmlspecialchars() above
$reclimit = 20;
$start = ($page - 1) * $reclimit;
$offset = ($page + 2) * $reclimit; // I want to get 60 results in total, or 3 pages of results.
$mysqli = new mysqli("localhost","username","password","db");
$stmt = $mysqli->prepare("SELECT title,description FROM content WHERE title LIKE ? LIMIT $start, $offset");
$stmt->bind_param('s', $term);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($title, $desc);
$rowcount = $stmt->num_rows; // This will get all results, regardless of `LIMIT`
$tpages = ceil($rowcount / $reclimit); // $rowcount returning incorrect integer messes up my pagination
echo $start;
echo $offset;
echo $rowcount;
echo $tpages; // Testing all variables to see which was the culprit
$wcount = 0;
$wmax = 20;
while(($stmt->fetch()) and ($wcount < $wmax))
{
// Echoing HTML --snipped--
$wcount++;
}
$stmt->close();
$mysqli->close();
}
I can't see anything I've done incorrectly, and it seems strange $rowcount
would return a value from all returned rows, regardless of LIMIT
as the data returned has been limited before the sum has been called. Have I misunderstood something?
Thanks for your time