Pagination using MySQL LIMIT, OFFSET - php

I have some code that LIMITs data to display only 4 items per page. The column I'm using has about 20-30 items, so I need to make those spread out across the pages.
On the first page, I have:
$result = mysqli_query($con,"SELECT * FROM menuitem LIMIT 4");
{
echo "<tr>";
echo "<td align='center'><img src=\"" . $row['picturepath'] . "\" /></td>";
echo "<td align='center'>" . $row['name'] . "</td> <td align='center'> <input type='button' value='More Info'; onclick=\"window.location='more_info.php?';\"> </td>";
echo "<td align='center'>" . $row['price'] . "</td> <td align='center'> <input type='button' value='Add to Order' onclick=''> </td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
<table width="1024" align="center" >
<tr height="50"></tr>
<tr>
<td width="80%" align="right">
NEXT
</td>
<td width="20%" align="right">
MAIN MENU
</td>
</tr>
</table>
You'll notice towards the bottom of the page my anchor tag within lists the second page, "itempage2.php". In item page 2, I have the same code, except my select statement lists the offset of 4.
$result = mysqli_query($con,"SELECT * FROM menuitem LIMIT 4 offset 4");
This works, this way when there is a pre-determined number of items within my database. But it's not that good. I need to create a new page only if there are more items, not hard-coded into it like it is now.
How can I create multiple pages without having to hard-code each new page, and offset?

First off, don't have a separate server script for each page, that is just madness. Most applications implement pagination via use of a pagination parameter in the URL. Something like:
http://yoursite.com/itempage.php?page=2
You can access the requested page number via $_GET['page'].
This makes your SQL formulation really easy:
// determine page number from $_GET
$page = 1;
if(!empty($_GET['page'])) {
$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
if(false === $page) {
$page = 1;
}
}
// set the number of items to display per page
$items_per_page = 4;
// build query
$offset = ($page - 1) * $items_per_page;
$sql = "SELECT * FROM menuitem LIMIT " . $offset . "," . $items_per_page;
So for example if input here was page=2, with 4 rows per page, your query would be:
SELECT * FROM menuitem LIMIT 4,4
So that is the basic problem of pagination. Now, you have the added requirement that you want to understand the total number of pages (so that you can determine if "NEXT PAGE" should be shown or if you wanted to allow direct access to page X via a link).
In order to do this, you must understand the number of rows in the table.
You can simply do this with a DB call before trying to return your actual limited record set (I say BEFORE since you obviously want to validate that the requested page exists).
This is actually quite simple:
$sql = "SELECT your_primary_key_field FROM menuitem";
$result = mysqli_query($con, $sql);
$row_count = mysqli_num_rows($result);
// free the result set as you don't need it anymore
mysqli_free_result($result);
$page_count = 0;
if (0 === $row_count) {
// maybe show some error since there is nothing in your table
} else {
// determine page_count
$page_count = (int)ceil($row_count / $items_per_page);
// double check that request page is in range
if($page > $page_count) {
// error to user, maybe set page to 1
$page = 1;
}
}
// make your LIMIT query here as shown above
// later when outputting page, you can simply work with $page and $page_count to output links
// for example
for ($i = 1; $i <= $page_count; $i++) {
if ($i === $page) { // this is current page
echo 'Page ' . $i . '<br>';
} else { // show link to other page
echo 'Page ' . $i . '<br>';
}
}

A dozen pages is not a big deal when using OFFSET. But when you have hundreds of pages, you will find that OFFSET is bad for performance. This is because all the skipped rows need to be read each time.
It is better to remember where you left off.

If you want to keep it simple go ahead and try this out.
$page_number = mysqli_escape_string($con, $_GET['page']);
$count_per_page = 20;
$next_offset = $page_number * $count_per_page;
$cat =mysqli_query($con, "SELECT * FROM categories LIMIT $count_per_page OFFSET $next_offset");
while ($row = mysqli_fetch_array($cat))
$count = $row[0];
The rest is up to you.
If you have result comming from two tables i suggest you try a different approach.

Use .. LIMIT :pageSize OFFSET :pageStart
Where :pageStart is bound to the_page_index (i.e. 0 for the first page) * number_of_items_per_pages (e.g. 4) and :pageSize is bound to number_of_items_per_pages.
To detect for "has more pages", either use SQL_CALC_FOUND_ROWS or use .. LIMIT :pageSize OFFSET :pageStart + 1 and detect a missing last (pageSize+1) record. Needless to say, for pages with an index > 0, there exists a previous page.
If the page index value is embedded in the URL (e.g. in "prev page" and "next page" links) then it can be obtained via the appropriate $_GET item.

Related

PHP If the number of an element was more than an amount, separate elements into two or more pages [duplicate]

I have some code that LIMITs data to display only 4 items per page. The column I'm using has about 20-30 items, so I need to make those spread out across the pages.
On the first page, I have:
$result = mysqli_query($con,"SELECT * FROM menuitem LIMIT 4");
{
echo "<tr>";
echo "<td align='center'><img src=\"" . $row['picturepath'] . "\" /></td>";
echo "<td align='center'>" . $row['name'] . "</td> <td align='center'> <input type='button' value='More Info'; onclick=\"window.location='more_info.php?';\"> </td>";
echo "<td align='center'>" . $row['price'] . "</td> <td align='center'> <input type='button' value='Add to Order' onclick=''> </td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
<table width="1024" align="center" >
<tr height="50"></tr>
<tr>
<td width="80%" align="right">
NEXT
</td>
<td width="20%" align="right">
MAIN MENU
</td>
</tr>
</table>
You'll notice towards the bottom of the page my anchor tag within lists the second page, "itempage2.php". In item page 2, I have the same code, except my select statement lists the offset of 4.
$result = mysqli_query($con,"SELECT * FROM menuitem LIMIT 4 offset 4");
This works, this way when there is a pre-determined number of items within my database. But it's not that good. I need to create a new page only if there are more items, not hard-coded into it like it is now.
How can I create multiple pages without having to hard-code each new page, and offset?
First off, don't have a separate server script for each page, that is just madness. Most applications implement pagination via use of a pagination parameter in the URL. Something like:
http://yoursite.com/itempage.php?page=2
You can access the requested page number via $_GET['page'].
This makes your SQL formulation really easy:
// determine page number from $_GET
$page = 1;
if(!empty($_GET['page'])) {
$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
if(false === $page) {
$page = 1;
}
}
// set the number of items to display per page
$items_per_page = 4;
// build query
$offset = ($page - 1) * $items_per_page;
$sql = "SELECT * FROM menuitem LIMIT " . $offset . "," . $items_per_page;
So for example if input here was page=2, with 4 rows per page, your query would be:
SELECT * FROM menuitem LIMIT 4,4
So that is the basic problem of pagination. Now, you have the added requirement that you want to understand the total number of pages (so that you can determine if "NEXT PAGE" should be shown or if you wanted to allow direct access to page X via a link).
In order to do this, you must understand the number of rows in the table.
You can simply do this with a DB call before trying to return your actual limited record set (I say BEFORE since you obviously want to validate that the requested page exists).
This is actually quite simple:
$sql = "SELECT your_primary_key_field FROM menuitem";
$result = mysqli_query($con, $sql);
$row_count = mysqli_num_rows($result);
// free the result set as you don't need it anymore
mysqli_free_result($result);
$page_count = 0;
if (0 === $row_count) {
// maybe show some error since there is nothing in your table
} else {
// determine page_count
$page_count = (int)ceil($row_count / $items_per_page);
// double check that request page is in range
if($page > $page_count) {
// error to user, maybe set page to 1
$page = 1;
}
}
// make your LIMIT query here as shown above
// later when outputting page, you can simply work with $page and $page_count to output links
// for example
for ($i = 1; $i <= $page_count; $i++) {
if ($i === $page) { // this is current page
echo 'Page ' . $i . '<br>';
} else { // show link to other page
echo 'Page ' . $i . '<br>';
}
}
A dozen pages is not a big deal when using OFFSET. But when you have hundreds of pages, you will find that OFFSET is bad for performance. This is because all the skipped rows need to be read each time.
It is better to remember where you left off.
If you want to keep it simple go ahead and try this out.
$page_number = mysqli_escape_string($con, $_GET['page']);
$count_per_page = 20;
$next_offset = $page_number * $count_per_page;
$cat =mysqli_query($con, "SELECT * FROM categories LIMIT $count_per_page OFFSET $next_offset");
while ($row = mysqli_fetch_array($cat))
$count = $row[0];
The rest is up to you.
If you have result comming from two tables i suggest you try a different approach.
Use .. LIMIT :pageSize OFFSET :pageStart
Where :pageStart is bound to the_page_index (i.e. 0 for the first page) * number_of_items_per_pages (e.g. 4) and :pageSize is bound to number_of_items_per_pages.
To detect for "has more pages", either use SQL_CALC_FOUND_ROWS or use .. LIMIT :pageSize OFFSET :pageStart + 1 and detect a missing last (pageSize+1) record. Needless to say, for pages with an index > 0, there exists a previous page.
If the page index value is embedded in the URL (e.g. in "prev page" and "next page" links) then it can be obtained via the appropriate $_GET item.

How do i get specific records with sql? [duplicate]

I have some code that LIMITs data to display only 4 items per page. The column I'm using has about 20-30 items, so I need to make those spread out across the pages.
On the first page, I have:
$result = mysqli_query($con,"SELECT * FROM menuitem LIMIT 4");
{
echo "<tr>";
echo "<td align='center'><img src=\"" . $row['picturepath'] . "\" /></td>";
echo "<td align='center'>" . $row['name'] . "</td> <td align='center'> <input type='button' value='More Info'; onclick=\"window.location='more_info.php?';\"> </td>";
echo "<td align='center'>" . $row['price'] . "</td> <td align='center'> <input type='button' value='Add to Order' onclick=''> </td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
<table width="1024" align="center" >
<tr height="50"></tr>
<tr>
<td width="80%" align="right">
NEXT
</td>
<td width="20%" align="right">
MAIN MENU
</td>
</tr>
</table>
You'll notice towards the bottom of the page my anchor tag within lists the second page, "itempage2.php". In item page 2, I have the same code, except my select statement lists the offset of 4.
$result = mysqli_query($con,"SELECT * FROM menuitem LIMIT 4 offset 4");
This works, this way when there is a pre-determined number of items within my database. But it's not that good. I need to create a new page only if there are more items, not hard-coded into it like it is now.
How can I create multiple pages without having to hard-code each new page, and offset?
First off, don't have a separate server script for each page, that is just madness. Most applications implement pagination via use of a pagination parameter in the URL. Something like:
http://yoursite.com/itempage.php?page=2
You can access the requested page number via $_GET['page'].
This makes your SQL formulation really easy:
// determine page number from $_GET
$page = 1;
if(!empty($_GET['page'])) {
$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
if(false === $page) {
$page = 1;
}
}
// set the number of items to display per page
$items_per_page = 4;
// build query
$offset = ($page - 1) * $items_per_page;
$sql = "SELECT * FROM menuitem LIMIT " . $offset . "," . $items_per_page;
So for example if input here was page=2, with 4 rows per page, your query would be:
SELECT * FROM menuitem LIMIT 4,4
So that is the basic problem of pagination. Now, you have the added requirement that you want to understand the total number of pages (so that you can determine if "NEXT PAGE" should be shown or if you wanted to allow direct access to page X via a link).
In order to do this, you must understand the number of rows in the table.
You can simply do this with a DB call before trying to return your actual limited record set (I say BEFORE since you obviously want to validate that the requested page exists).
This is actually quite simple:
$sql = "SELECT your_primary_key_field FROM menuitem";
$result = mysqli_query($con, $sql);
$row_count = mysqli_num_rows($result);
// free the result set as you don't need it anymore
mysqli_free_result($result);
$page_count = 0;
if (0 === $row_count) {
// maybe show some error since there is nothing in your table
} else {
// determine page_count
$page_count = (int)ceil($row_count / $items_per_page);
// double check that request page is in range
if($page > $page_count) {
// error to user, maybe set page to 1
$page = 1;
}
}
// make your LIMIT query here as shown above
// later when outputting page, you can simply work with $page and $page_count to output links
// for example
for ($i = 1; $i <= $page_count; $i++) {
if ($i === $page) { // this is current page
echo 'Page ' . $i . '<br>';
} else { // show link to other page
echo 'Page ' . $i . '<br>';
}
}
A dozen pages is not a big deal when using OFFSET. But when you have hundreds of pages, you will find that OFFSET is bad for performance. This is because all the skipped rows need to be read each time.
It is better to remember where you left off.
If you want to keep it simple go ahead and try this out.
$page_number = mysqli_escape_string($con, $_GET['page']);
$count_per_page = 20;
$next_offset = $page_number * $count_per_page;
$cat =mysqli_query($con, "SELECT * FROM categories LIMIT $count_per_page OFFSET $next_offset");
while ($row = mysqli_fetch_array($cat))
$count = $row[0];
The rest is up to you.
If you have result comming from two tables i suggest you try a different approach.
Use .. LIMIT :pageSize OFFSET :pageStart
Where :pageStart is bound to the_page_index (i.e. 0 for the first page) * number_of_items_per_pages (e.g. 4) and :pageSize is bound to number_of_items_per_pages.
To detect for "has more pages", either use SQL_CALC_FOUND_ROWS or use .. LIMIT :pageSize OFFSET :pageStart + 1 and detect a missing last (pageSize+1) record. Needless to say, for pages with an index > 0, there exists a previous page.
If the page index value is embedded in the URL (e.g. in "prev page" and "next page" links) then it can be obtained via the appropriate $_GET item.

Count rows with variable and pagination?

I recently had a script that worked where I could count the rows in a table with a variable like so:
$i = 1;
while($row = mysqli_fetch_array($query5)) {
echo "$i";
echo "<br />";
$i++;
}
However, I recently implemented this pagination script here http://papermashup.com/easy-php-pagination/ which ruins it. As I go to the second page, it counts the rows all over again and starts identifying each row as #1. However, I would like it to continue to name the same row # from the previous page. Is this possible?
You must have page number somewhere, so start counting from page number * items per page
$i = $page_number * $page_size + 1;// assuming page_number starts from 0
while($row = mysqli_fetch_array($query5))
{
echo "$i";
echo "<br />";
$i++;
}

PHP MySQL using isset($_GET)

Hello, I have my php script using this code:
$start = (isset($_GET['start']) ? (int)$_GET['start'] : 0);
$result = mysqli_query($con,"SELECT * FROM menuitem LIMIT $start, 4");
This pulls in the data from my database fine. Now I want to load the next 4 items from my database when a user clicks the "Next items" link, so I put this in my code:
echo "<table width=\"1024\" align=\"center\" >";
echo "<tr height=\"50\"></tr>";
$next = $start + 4;
echo 'Next items';
echo "</table>";
Clicking the "Next items" link loads the url firstpage.php?start= but it doesn't load the next four items. Anyone see what i'm doing wrong?
You're using the wrong combination of quotes when outputting the link:
echo 'Next items';
// unneeded double quote before your $next variable

Pagination Error

Im trying to do pages for my search result.My Search function is working fine. However, when I click on the page number. This error appears (below) :
Notice: Undefined index: search in C:\wamp\www\I-Document\new.php on line 8
ERROR: Select from dropdown
This message only should appear when there is no input in dropdown and no search input.
Im not sure how to correct this. Please help! Thank u
<?php
//connecting to the database
include 'config.php';
$search = mysql_escape_string($_POST['search']);
$dropdown = mysql_escape_string($_POST['dropdown']);
if (empty($search) && empty($dropdown)) {
die("Please choose your Search Criteria");
}
//max displayed per page
$per_page = 10;
//get start variable
$start = $_GET['start'];
//count records
$record_count = mysql_query("SELECT COUNT(*) FROM document WHERE $dropdown LIKE '%$search%'");
//count max pages
$max_pages = $record_count / $per_page;
if (!$start)
$start = 0;
//display data
$query = mysql_query("SELECT *
FROM document
WHERE $dropdown LIKE '%$search%'
LIMIT $start, $per_page");
echo "<b><center>Search Result</center></b><br>";
$num=mysql_num_rows($query);
if ($num==0)
echo "No results found";
else {
echo "$num results found!<p>";
}
echo "You searched for <b>$search</b><br /><br /><hr size='1'>";
echo "<table border='1' width='600'>
<th>File Reference No.</th>
<th>File Name</th>
<th>Owner</th>
<th>Borrow</th>
</tr>";
while ($rows = mysql_fetch_assoc($query)) {
echo "<tr>";
echo "<td>". $rows['file_ref'] ."</td>";
echo "<td>". $rows['file_name'] ."</td>";
echo "<td>". $rows['owner'] ."</td>";
echo "<td>Borrow</td>";
echo "</tr>";
}
echo "</table>";
//setup prev and next variables
$prev = $start - $per_page;
$next = $start + $per_page;
//show prev button
if (!($start<=0))
echo "<a href='new.php?start=$prev'>Prev</a> ";
//show page numbers
//set variable for first page
$i=1;
for ($x=0;$x<$record_count;$x=$x+$per_page) {
if ($start!=$x)
echo " <a href='new.php?start=$x'>$i</a> ";
else
echo " <a href='new.php?start=$x'><b>$i</b></a> ";
$i++;
}
}
//show next button
if (!($start>=$record_count-$per_page))
echo " <a href='new.php?start=$next'>Next</a>";
?>
Looks to me like when you click on a link, you no longer have the POST data being sent (it becomes a simple GET request). You'll need to create a form, then have a submit button for each of the pages. Or have the search term in the Query String, like Google (google.com/search?q=your+search+term+here)
This is the offending line
$search = mysql_escape_string($_POST['search']);
Your logic goes
IF $_POST['submit'] IS NOT SET
THEN
$search = mysql_escape_string($_POST['search']);
It's a pretty safe bet to say that if $_POST['submit'] is not set, then neither is $_POST['search']
Also, consider when you click one of your "page" links, that will issue a GET request and $_POST will be empty. You can either pass your POST parameters via GET along with the pagination data and look for them in either $_GET or $_POST (or $_REQUEST if you're feeling saucy), or create your pagination control as a "postable" form.
You already have all the code. You just need to rewrite your error condition.
Get the input variables
Encode them
Test for presence of both or die() with error message
So from your description:
$search = mysql_escape_string($_POST['search']);
$dropdown = mysql_escape_string($_POST['dropdown']);
if (empty($search) && empty($dropdown)) {
die("ERROR: whatever");
}
In this case you can test with empty() even after the escaping, because it would be an empty string in any case.
if (isset($_POST["search"])){
$search = mysql_escape_string($_POST['search']);
}else{
$search = mysql_escape_string($_GET['search']);
}
do the same for $_POST['dropdown']
but when printing out each page link , you should add the &search= and &dropdown= in the href of the page number .

Categories