Pagination - Counting from 0 without mysql_result (shows error) - php

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 */

Related

pagination with dots in middle generate with PHP

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}"

How to hide the next button when no pages to dispaly

Can someone help me please? I am sure it is easy for you guys. I am battling to find a solution on how to hide the next link when there are no pages to display my code is as follows:
if (!isset($_GET['page']) or !is_numeric($_GET['page'])) {
$page = 0;
} else {
$page = (int)$_GET['page'];
}
$pages_query=mysql_query ("SELECT COUNT * FROM hardware");
$result = mysql_query("SELECT * FROM hardware LIMIT $page, 3");
echo 'Next<p>';
$prev = $page - 3;
//only print a "Previous" link if a "Next" was clicked
if ($prev >= 0) {
echo 'Previous';
}
You can use mysql_num_rows($result) to get the number of records in hardware:
$result = mysql_query("SELECT * FROM hardware LIMIT $page, 3");
$record_count = mysql_num_rows($result);
if ($record_count > 1)
echo 'Next';
in your if statement check if the $page is greater than 0 then according to the outcome of the value of $page write your code. you can use another if statement in the first if statement and make it detect the situation and decide what to do. The other thing is if the user clicked next then the user is on the second page so your previous should appear if $prev is higher than 1 it should make it
something along the lines of:
$itemsPerPage = 3;
$sql = "SELECT * FROM hardware";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
$pageCount = $count/$itemsPerPage;
if($pageCount > $page) { //Are there more pages worth of items stored, than we're currently looking at?
echo 'next';
}
You want to be using OFFSET in your SQL syntax, as well as LIMIT.
LIMIT limits the number of rows returned.
OFFSET tells it to start a number of rows into the result set.
You need to limit to the number of items you want on a page. and offset by that number*page.
Hopes this helps.

echo a certain number of results per page in php

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

How to split search results into pages?

How to split the search results into pages? (like page 1, page 2, page 3...)
When the user searches for products on my e-commerce website, I want results to be split into several pages showing around 20 products per page. The search results are the outcome of database query.
For example: If the user searches for Samsung mobiles so my query will be:
SELECT * FROM PRODUCTS WHERE BRAND='SAMSUNG';
Suppose the above query returns 55 results, how to show them into pages (1,2 and 3)?
I am using PHP, MySQL, Apache on Windows machine.
The appropriate SQL would be adding:
LIMIT start, amount
You can navigate like
search.php?start=20
and then code like:
LIMIT $start, $amount
with
$start = intval($_GET['start']);
and
$amount = 20;
That will result in max 20 records a page.
Use SQL's LIMIT keyword to limit the amount of results from your query; for example:
SELECT * FROM PRODUCTS WHERE BRAND='SAMSUNG' LIMIT 20, 40;
This would select 20 elements, starting at the 40th
Here is the complete code:
<?php
// Requested page
$requested_page = isset($_GET['page']) ? intval($_GET['page']) : 1;
// Get the product count
$r = mysql_query("SELECT COUNT(*) FROM PRODUCTS WHERE BRAND='SAMSUNG'");
$d = mysql_fetch_row($r);
$product_count = $d[0];
$products_per_page = 20;
// 55 products => $page_count = 3
$page_count = ceil($product_count / $products_per_page);
// You can check if $requested_page is > to $page_count OR < 1,
// and redirect to the page one.
$first_product_shown = ($requested_page - 1) * $products_per_page;
// Ok, we write the page links
echo '<p>';
for($i=1; $i<=$page_count; $i++) {
if($i == $requested_page) {
echo $i;
} else {
echo ''.$i.' ';
}
}
echo '</p>';
// Then we retrieve the data for this requested page
$r = mysql_query("SELECT * FROM PRODUCTS WHERE BRAND='SAMSUNG' LIMIT $first_product_shown, $products_per_page");
while($d = mysql_fetch_assoc($r)) {
var_dump($d);
}
?>
Hope its help.
Yes you can run a query to get total record count and than use query using limit
exampe:
select count(id) from table_name
This will return total record count in database
In my php learning books, it provides a solution using a PHP class
it looks like this
<!-- language: php -->
<?php
error_reporting(0); // disable the annoying error report
class page_class
{
// Properties
var $current_page;
var $amount_of_data;
var $page_total;
var $row_per_page;
// Constructor
function page_class($rows_per_page)
{
$this->row_per_page = $rows_per_page;
$this->current_page = $_GET['page'];
if (empty($this->current_page))
$this->current_page = 1;
}
function specify_row_counts($amount)
{
$this->amount_of_data = $amount;
$this->page_total=
ceil($amount / $this->row_per_page);
}
function get_starting_record()
{
$starting_record = ($this->current_page - 1) *
$this->row_per_page;
return $starting_record;
}
function show_pages_link()
{
if ($this->page_total > 1)
{
print("<center><div class=\"notice\"><span class=\"note\">Halaman: ");
for ($hal = 1; $hal <= $this->page_total; $hal++)
{
if ($hal == $this->current_page)
echo "$hal | ";
else
{
$script_name = $_SERVER['PHP_SELF'];
echo "$hal |\n";
}
}
}
}
}
?>
then we call it on the script that require paging
<!-- language: php -->
<?php $per_page = 5;
$page = new Page_class($per_page);
error_reporting(0); // disable the annoying error report
$sql="SELECT * FROM table WHERE condition GROUP BY group";
$result=mysql_query($sql) or die('error'.mysql_error());
// paging start
$row_counts = mysql_num_rows($result);
$page->specify_row_counts($row_counts);
$starting_record = $page->get_starting_record();
$sql="SELECT * FROM table WHERE condition GROUP BY group LIMIT $starting_record, $per_page";
$result=mysql_query($sql) or die('error'.mysql_error());
$number = $starting_record; //numbering
$num_rows = mysql_num_rows($result);
if ($num_rows == 0 )
{ // if no result is found
echo "<div class=\"notice\">
<center><span class=note>NO DATA</span></center>
</div>";
}
else {
// while goes here ...
}
?>
// call the page link
<?php
$page->show_pages_link();
?>
hope it helps, just tried it hours ago to my search script page (learning from books)

php my sql pagination help need for links and advancing the next offset

hi i'm trying to paginate a php mysql database, and I can't figure out what make the results move to the next page, it's stuck at record row zero and what do i change to make it go to the next set of results? is this the offset hooked to the nav link somehow does it have to recall a mysql query? how does this work?
//pagination
//find out how many rows are in the table
$sql = "SELECT * FROM hotels_database";
$result = mysql_query($sql, $con) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];
// number of rows to show per page
$rowsperpage = 2;
// 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 = preg_replace('#[^0-9]#i','', $_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
$sql = "SELECT * FROM hotels_database LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $con) or trigger_error("SQL", E_USER_ERROR);
// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) {
// echo data
for ($stars=1;$stars<=floor($list['stars']);$stars++){
$star_string .= "<img src='images/star.jpg'/>";
}
if (($list['stars']-floor($list['stars']))> 0){
$star_string .= "<img src='images/half_star.jpg'/>";
}
$hotels_database .= "<div style='display:table-row;height:70px;'><div style='width:60px;height:60px;display:table-cell;float:left;'><img src='".$list['pic']."' width='60px'/></div>"."<div style='width:280px;display:table-cell;vertical-align:top;text-align:left;padding-left:5px;font-size:12px;'><a href='#' class='database_link'>".$list['hotel']."</a>".$star_string."<br/><span style='font-size:10px;'>".$list['addy']."</span><br/>Guest score: <span style='color:red;font-size:14px;'>".$list['score']."</span> out of 10"."<br/>"."<li class='database_arrow'>Display Amenities & More Info</li>"."</div>"."<div style='width:78px;height:60px;display:table-cell;vertical-align:top;'><span style='font-family:arial;color:green;font-size:15px;'>$".$list['price']."</span><br/>per night<div style='border-radius:10px;background-color:#1284d3;height:25px;width:70px;left:10px;top:10px;position:relative;border:1px black solid;color:white;font-family:arial;line-height:8px;'><br/>select</div><br/></div>"."</div><hr style='color:#c8ff78;'/>";
$star_string="";
} // end while
/****** build the pagination links ******/
// range of num links to show
//pagination
/*
ya, so i can't figure out how to go to the next offset what href do i use in this case? and why isn't the currentpage query string being displayed in my addy bar? please take a look,
As D.N said code would be helpful but in general it goes
if(isset($_GET['offset']) {
$offset = $_get['offset'];
}
else{
$offset = 0;
}
then in the SQL call you add:
'what ever the call is' "limit $limit offset $offset"

Categories