I am creating a pagination script and I need to get the first and last results in the database query so that I can determine what results appear when the user clicks a page to go to. This is the code that I have at the minute:
// my database connection is opened
// this gets all of the entries in the database
$q = mysql_query("SELECT * FROM my_table ORDER BY id ASC");
$count = mysql_num_rows($q);
// this is how many results I want to display
$max = 2;
// this determines how many pages there will be
$pages = round($count/$max,0);
// this is where I think my script goes wrong
// I want to get the last result of the first page
// or the first result of the previous page
// so the query can start where the last query left off
// I've tried a few different things to get this script to work
// but I think that I need to get the first or last result of the previous page
// but I don't know how to.
$get = $_GET['p'];
$pn = $_GET['pn'];
$pq = mysql_query("SELECT * FROM my_table ORDER BY id ASC LIMIT $max OFFSET $get");
// my query results appear
if(!$pn) {
$pn = 1;
}
echo "</table><br />
Page $pn of $pages<br />";
for($p = 1;$p<=$pages;$p++) {
echo "<a href='javascript:void(0);' onclick='nextPage($max, $p);' title='Page $p'>Page $p</a> ";
}
I think you have few problems there, but I try to tackle them for you. First, as comments say above, you are using code that it vulnerable to SQL injection. Take care of that – you might want to use PDO, which is as easy use as MySQL extension, and will save you from many trouble (like injection).
But to your code, lets go through it:
SELECT count(*) FROM mytable.$pagesuse ceil() as you want all rows to be printed, if you have$max5 and have 11 rows, round will make$pages2, where you actually want 3 (last page just contains that last 11th row)LIMIT row_count OFFSET offset. You can calculate offset from page number, so:$max = row_countbut$offset = ($max * $page) - $max. In your code if$getis directly the page, it means you get $get’th row (Not sure though what happens in your JS nextpage. Bare in mind that not all use JavaScript.)I have prepared simple example here which uses PDO, maybe that gives you idea how simple it’s use PDO.
The selecting rows shows example how to put parameters in SQL, it would be perfectly safe in this case state,
'SELECT * FROM pseudorows LIMIT '.$start.','.$maxby I wanted to make an example how easy it is (and then safe):