Im trying to create pagination using PHP but I have issue with quantity of page.
my pagination created used
foreach(range(1, $pager) as $i){
echo '<span class="pagination-num" data-pager="'.$i.'">'.$i.'</span>';
}
the problem comes when the range is too large. like on the image below. variable $pager contains a dynamic value. $pager counts how many pages should created from quantity of the content.
I set 10 content per page, so if there is 100 content:
$pager = ceil($content / 10);
it's there any way to edit pagination with dots. (next and prev I created using custom Jquery).
first of all you need to set items per page for example 10 items per page
<?php
$ipp = 10; //Item Per Page
if(isset($_GET["page"]) AND $_GET["page"] > 0){
$page_number = $_GET['page']; // page number
}
else{$page_number = 1;}
$total_items = 100; //total items
$total_pages = ceil($total_items/$ipp); //total pages
$page_position = (($page_number-1) * $ipp); //page position
?>
just in case if you are using sql:
"SELECT * FROM `table` WHERE --something-- ORDER BY `id` ASC LIMIT {$page_position}, {$ipp}"
Related
I am working on paginating my MySQL results to 10 per page. So far, I have been able the count how many results there are in the column, count how many pages there will be if there are 10 results/page, display the number of pages and also add links to each page (ex: Page1, Page2, Page 3, Page 4...)
Currently, all 38 results are showing on one page. When I click the page number, I am taken to the correct link but the content with the 38 results is the same. I know I need to divide the 38 results into the four pages. This is where I'm stuck at:
To find the number of pages, I have variable:
$pages = ceil($items_number / $per_page )
However, on multiple tutorials I've seen:
$pages = ceil(mysql_results($items_number,0) / $per_page )
which allows the data count to start at 0. When I tried this, I get an error
Fatal error: Call to undefined function mysql_results()
So I don't have the option to start counting results from 0 (using mysql_result) and break them into 10 per page.
How can I get around the mysql_result and be able to show the appropriate data/number of items for each page number?
Here's a link, clickable page numbers are on top:
http://test.ishabagha.com/classic_cars/pag_test.php
Code:
<?php
require_once("./includes/database_connection.php");
error_reporting(E_ALL);
ini_set('display_errors', 1);
$page = "";
$per_page = 10;
$query = "SELECT productCode, productName, productLine, productScale, productVendor, productDescription, buyPrice FROM products WHERE `productLine` = 'Classic Cars'";
$result = mysqli_query($dbc, $query)
or die(mysqli_error($dbc));
$query_count = "SELECT count(productLine) FROM products WHERE productLine = 'Classic Cars'";
$items = mysqli_query($dbc, $query_count)
or die(mysqli_error($dbc));
$row = mysqli_fetch_row($items);
$items_number = $row[0];
$pages = ceil($items_number / $per_page )
?>
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>Home</title>
<link type="text/css" rel="stylesheet" href="classic_cars.css" />
</head>
<body>
<?php
require_once("./includes/navigation.php");
?>
<?php
for($number = 1; $number <= $pages; $number++) {
echo "<a href='?page=$number'>$number</a>";
}
while ($row = mysqli_fetch_array($result)) {
$product_code = $row['productCode'];
$product_name = $row['productName'];
$product_line = $row['productLine'];
$product_vendor = $row['productVendor'];
$product_description = $row['productDescription'];
$buy_price = $row['buyPrice'];
echo "<tr>
<td><p>$product_name</p></td>
</tr>";
} // end while ($row = mysqli_fetch_array($result))
?>
<?php
require_once("./includes/footer.php");
?>
</body>
</html>
Note:
It means that you are mixing deprecated mysql_* API with mysqli_*. You should use only one API in your project, and I would recommend to use mysqli_* only.
You forgot ; in your ceil($items_number / $per_page )
All the results are showing because you did not set a LIMIT on your query inside $query
In order to do this, you should know what page you are currently in your pagination
Get first the number of total rows (replace your previous one):
$items_number = mysqli_num_rows($items);
Let us determine what page you are currently, using $_GET["page"]. If no page is found in your URL, the default page to show is the first one.
Put this after your $pages = ceil($items_number / $per_page);
if (isset($_GET['page']) && is_numeric($_GET['page'])) { /* IF PAGE NUMBER IS VALID */
$currentpage = (int) $_GET['page']; /* STORE THE CURRENT PAGE */
} else {
$currentpage = 1; /* DEFAULT PAGE IS SET TO 1 */
}
if ($currentpage > $pages) { /* IF CURRENT PAGE IS 2 OR MORE */
$currentpage = $pages;
}
if ($currentpage < 1) { /* IF CURRENT PAGE IS LESS THAN 1, WHICH WE SHOULD PREVENT */
$currentpage = 1; /* DEFAULT PAGE IS SET TO 1 */
}
$offset = ($currentpage - 1) * $per_page; /* SET AN OFFSET FOR YOUR QUERY LATER */
Your query should look like this instead:
$query = "SELECT productCode, productName, productLine, productScale, productVendor, productDescription, buyPrice
FROM products
WHERE `productLine` = 'Classic Cars'
LIMIT $offset, $per_page"; /* LIMITS THE NUMBER TO SHOW IN A PAGE */
But we should move this query, and also the execution after the first code I had given above. So the arrangement is:
$query_count = "SELECT productLine FROM products WHERE productLine = 'Classic Cars'";
$items = mysqli_query($dbc, $query_count) /* EXECUTE THE QUERY */
or die(mysqli_error($dbc));
$items_number = mysqli_num_rows($items); /* GET THE NUMBER OF RESULTS */
$items_number = number_format($items_number); /* SECURE THE FORMAT THAT IT IS A NUMBER */
$per_page = 10; /* NUMBER OF ROWS TO SHOW PER PAGE */
$pages = ceil($items_number / $per_page );
/* THE CODE I HAD GIVEN THAT GETS THE CURRENT PAGE AND DEFINES THE $offset */
/* THEN THE QUERY THAT LIMITS THE NUMBER OF ROWS TO FETCH */
/* THEN YOU FETCH THE RESULT, AND THEN THE HTML */
I have a query and loop that displays products depending on an id. Sub-Category id in this case. The code is as follows:
<div id="categoryproducts">
<?php
$productsGet = mssql_query("SELECT * FROM Products WHERE SubCatID = ".$_GET['scid']."");
while ($echoProds = mssql_fetch_array($productsGet)) {
?>
<div class="productbox">
<div class="productboximg">
<img src="<?php echo $echoProds['ProdThumb']; ?>" height="58" width="70" alt="" />
</div>
<div class="productboxdtl">
<h3><?php echo $echoProds['Title']; ?></h3>
<p><?php echo $echoProds['Synopsis']; ?></p>
</div>
<div class="productboxprc">
Price <strong>£<?php echo $echoProds['Price']; ?></strong>
</div>
<div class="productboxmore">
</div>
</div>
<?php
}
?>
<div id="shoplistpagesbot" class="shoplistpages">
Results Pages: 1 2 [Next »]
</div>
I am unsure how to display a certain number of products per page, as shown there is a mechanism for changing between pages, I need to somehow code that after a certain number of products, say 5 for example, the remainder are displayed on the next page.
Can anyone suggest how to do this? Or point me in the correct dirrection as to which functions I should be looking into.
Sorry if it isn't very clear, I am new to PHP. The DB im using is a MS SQL one not MySQL
Depends what version of MSSQL you are using.
I'm not a user of MSSQL, but apparently the SQL Server 2000 uses the TOP command, whilst SQL Server 2005 uses the BETWEEN command. A Google search should provide you with several tutorials on each but I am going to assume that you are using the 2005 version.
To return the items on page number $page_number, the general algorithm is :
// The most common way to specify which page to display is a GET variable. There
// are others ways and if you'd prefer them, just set $page_number to get the
// number from there instead. Don't forget to filter all data from the GET array
// as a user may try to insert harmful data, such as XSS attacks.
$page_number = $_GET['page'];
$scid = $_GET['scid'];
// Calculate the range of items to display.
$min = $page_number * $items_per_page;
$max = $min + $items_per_page;
$sql = "SELECT * FROM Products WHERE SubCatID = \"{$scid}\" BETWEEN {$min} AND {$max}";
To get the remaining number of items, you'll need a separate database query returning the total number of items.
$sql = "SELECT COUNT(*) FROM Products WHERE SubCatID = \"{$scid}\"";
// Using the same $max as before as it is the number of items on the page plus
// total items on previous pages, but we'll redefine it here just in case.
$max = ($page_number * $items_per_page) + $items_per_page;
// Assume that $total_rows is the number returned from executing the count query.
$remaining_items = $total_rows - $max;
Now to generate links to all the other pages.
$current_page = $_GET['page'];
$total_pages = $total_rows / $items_per_page;
if($current_page != 1) {
$previous = $current_page - 1;
echo "Previous";
}
for($i = 1; $i <= $total_pages; $i++) {
echo "{$i}";
}
if($current_page != $total_pages) {
$next = $current_page + 1;
echo "Next";
}
$pagenumber = $_GET['pagenumber'];
$recordsperpage = 30;
$first = ($pagenumber*$recordperpage)-$recordperpage;
$last = $pagenumber*$recordsperpage;
$productsGet = mysql_query("SELECT * FROM Products WHERE SubCatID = '".$_GET['scid']."' LIMIT $first,$last");
Have this at the top of the page and pass a GET parameter in your links e.g. browse.php?pagenumber=1;
You can calculate the number of pages by dividing total rows in the recordset by your $recordsperpage variable.
Then just use a simple for loop to output the navigation links e.g.:
for($i = 1; $i <= $totalpages; $i++) {
echo "<a href='browse.php?pagenumber=$i'>$i</a>";
}
Where $totalpages is the result of dividing total rows in the recordset by your $recordsperpage variable.
Hope this helps
Here it is for MS SQL:
SELECT TOP 10 *
FROM (SELECT TOP 20 * FROM products ORDER BY ID) as T
ORDER BY ID DESC
Basically are selecting the top 10 records from the top 20 in reverse order here. Hence you get the second 10 in the recordset.
Replace the 10 with the number of records per page and the 20 with the $last variable above.
Hope this clears it up
*EDIT***
I've made great progress by combining the main query that pulls the airwaves with some variables from the pagination query and have finally gotten the pagination to work. The only problem now is that the first page is blank and page two is correct starting with result 41-80
Here is the query that limits and pulls the airwaves
$rowsperpage = 40;
$currentpage = (int) $_GET['currentpage'];
$offset = ($currentpage - 1) * $rowsperpage;
$query = "SELECT * FROM `CysticAirwaves` WHERE `FromUserID` = `ToUserID` AND `status` = 'active' ORDER BY `date` DESC, `time` DESC LIMIT $offset, $rowsperpage" ;
$request = mysql_query($query,$connection);
$counter = 0;
while($result = mysql_fetch_array($request)) {
and here is the pagination code:
$query = "SELECT COUNT(*) FROM `CysticAirwaves`";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];
// number of rows to show per page
$rowsperpage = 40;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);
// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
// cast var as int
$currentpage = (int) $_GET['currentpage'];
} else {
// default page num
$currentpage = 1;
} // end if
// if current page is greater than total pages...
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
} // end if
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;
// get the info from the db
$query2 = "SELECT `id` FROM `CysticAirwaves` LIMIT $offset, $rowsperpage";
$result = mysql_query($query2, $connection) or trigger_error("SQL", E_USER_ERROR);
// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) {
// echo data
echo $list['id'] . " : " . $list['number'] . "<br />";
} // end while
/****** build the pagination links ******/
// range of num links to show
$range = 3;
// if not on page 1, don't show back links
if ($currentpage > 1) {
// show << link to go back to page 1
echo " <a href='http://www.cysticlife.org/Airwave_build.php?currentpage=1'><<</a> ";
// get previous page num
$prevpage = $currentpage - 1;
// show < link to go back to 1 page
echo " <a href='http://www.cysticlife.org/Airwave_build.php?currentpage=$prevpage'><</a> ";
} // end if
// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > 0) && ($x <= $totalpages)) {
// if we're on current page...
if ($x == $currentpage) {
// 'highlight' it but don't make a link
echo " [<b>$x</b>] ";
// if not current page...
} else {
// make it a link
echo " <a href='http://www.cysticlife.org/Airwave_build.php?currentpage=$x'>$x</a> ";
} // end else
} // end if
} // end for
// if not on last page, show forward and last page links
if ($currentpage != $totalpages) {
// get next page
$nextpage = $currentpage + 1;
// echo forward link for next page
echo " <a href='http://www.cysticlife.org/Airwave_build.php?currentpage=$nextpage'>></a> ";
// echo forward link for lastpage
echo " <a href='http://www.cysticlife.org/Airwave_build.php?currentpage=$totalpages'>>></a> ";
} // end if
/****** end build pagination links ******/
?>
So long story short, I just am not able to pull the first 40 results but after that its fine
This is a better way to go about pagination:
SELECT SQL_CALC_FOUND_ROWS id FROM `CysticAirwaves` LIMIT $offset, $rowsperpage
Select the data you want to display using the example query above which will return the same result as your query2
Then execute another SQL query:
SELECT FOUND_ROWS()
This will return the number of rows found without using a limit. See more here:
http://dev.mysql.com/doc/refman/5.0/en/limit-optimization.html
This would be the fastest way to manage pagination.
You would then loop through the results of your first query and display then. All you need to keep track of is what page you are on, and how many rows to show per page.
If you page number * $rowsperpage > the result of the second select (FOUND_ROWS) then you do not need to calculate or show the 'next' pages options/links.
For 'next' pages, loop 3 times incrementing the page number or next page * $rowsperpage > total rows.
For 'previous' pages, loop 3 times decrementing the page number or previous page = 1 (break out of loop in this case).
That should do the trick.
Probably you code so much, that it's hard to read what you've once written. You seem to put a comment next to each line of code, which might underline that. So you probably should reduce the code to reduce this problem.
This is just a suggestion, you wrote:
// if current page is greater than total pages...
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
} // end if
All these if clauses you need to deal with! All these comments to read! Isn't that a burden?
// currentpage must be within 1 and total of pages.
$currentpage = max(1,min($totalpages, $currentpage));
How about that? If you have problems to understand it, you can put some comments on top that explain it as you do as well in your code - in your words if mine are not fitting, it's just a suggestion.
I've tried a load of different code snippets that are out there for using pagination in my result set. I've got the same problem in each case. Using LIMIT on the end of the query I can display the first page correctly along with the navigation links for the correct number of pages (so the code doing the calculations with number of rows returned and number to display on each page is right), but when you click to follow the link to any of the other pages then they're blank. So how do I get the updated query to run again and display my results on the subsequent pages?
This is one piece of code that I've tried:
$rowsperpage = 10;
$totalpages = ceil($numrows / $rowsperpage);
// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) { $currentpage = (int) $_GET['currentpage']; }
else { $currentpage = 1; }
// if current page is greater than total pages...
if ($currentpage > $totalpages) { $currentpage = $totalpages; }
// if current page is less than first page...
if ($currentpage < 1) { $currentpage = 1; }
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;
// run the query
$sql = "SELECT * FROM table WHERE keyword LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $link) or trigger_error("SQL", E_USER_ERROR);
// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result))
{
//echo data for each record here
}
// building pagination links
$range = 3;
// if not on page 1, don't show back links
if ($currentpage > 1) {
// show << link to go back to page 1
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
// get previous page num
$prevpage = $currentpage - 1;
// show < link to go back to 1 page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
} // end if
Not permitted to show rest of navigation code due to too many hrefs, but the links appear correctly. The problem seems to be how the query is carried over to the next page.
You have to use limit offset, rowcount.
Typically for nth page
offset= (n-1)*pagesize and rowcount=pagesize
Is it possible to create pagination without getting all elements of table?
But with pages in GET like /1 /666…
It usually involves issuing two queries: one to get your "slice" of the result set, and one to get the total number of records. From there, you can work out how many pages you have and build pagination accordingly.
A simply example:
<?php
$where = ""; // your WHERE clause would go in here
$batch = 10; // how many results to show at any one time
$page = (intval($_GET['page']) > 0) ? intval($_GET['page']) : 1;
$start = $page-1/$batch;
$pages = ceil($total/$batch);
$sql = "SELECT COUNT(*) AS total FROM tbl $where";
$res = mysql_query($sql);
$row = mysql_fetch_assoc($res);
$total = $row['total'];
// start pagination
$paging = '<p class="paging">Pages:';
for ($i=1; $i <= $pages; $i++) {
if ($i==$page) {
$paging.= sprintf(' <span class="current">%d</a>', $i);
} else {
$paging.= sprintf(' %1$d', $i);
}
}
$paging.= sprintf' (%d total; showing %d to %d)', $total, $start+1, min($total, $start+$batch));
And then to see your pagination links:
...
// loop over result set here
// render pagination links
echo $paging;
I hope this helps.
Yes, using mySQL's LIMIT clause. Most pagination tutorials make good examples of how to use it.
See these questions for further links and information:
How do you implement pagination in PHP?
Searching for advanced php/mysql pagination script
more results
You can use LIMIT to paginate over your result set.
SELECT * FROM comments WHERE post_id = 1 LIMIT 5, 10
where LIMIT 5 means 5 comments and 10 is the offset. You can also use the longer syntax:
... LIMIT 5 OFFSET 10