How to specify the number of pages shown? - php

Pagination PHP code:
<?php
//Connecting To The DB And Fetching Number Of Rows.
$stmt = $pdo->prepare('SELECT * FROM locations');
$stmt->execute();
$count = $stmt->rowCount();
$values = $stmt->fetchAll();
//Check If Page Number Is Set To Specific Value.
if (isset($_GET['pageno']))
{
$pageno = $_GET['pageno']; //Current Page Number.
$no_of_records_per_page = 100; // Number Of Rows Per Page.
$total_pages = ceil($count / $no_of_records_per_page); //Total Number Of Pages.
$offset = ($pageno-1) * $no_of_records_per_page; //Starting From.
}
//If Page Number Not Specified The First Page Will Be Shown.
else
{
$pageno = 1;
}
?>
HTML code beneath it:
<ul class="pagination">
//First Page.
<li>
First
</li>
//Previous Page.
<li>
Prev
</li>
<li>
//Loop Through Pages.
<?php
for ($i=1; $i <= $total_pages ; $i++)
{
echo ''.$i.'';
}
?>
</li>
//Next Page.
<li>
Next
</li>
//Last Page.
<li>
Last
</li>
It's showing all the pages:
First Previous 1 2 3 4 5 6 7 8 Next Last
But if there are many pages it would be missed up.
I want to show specific number of pages like 5 or 6:
First Previous 1 2 3 4 5 .. .. 8 Next Last
Is it possible ? Is there is a library / plugin for that?

Best use Data tables which will process the data server side, which will be your ajax call and data will load on click on next or on pagination. it will reduce the load of getting data at one go and you do not have to write separate code for the pagination too.
Refer below link.
https://datatables.net/examples/data_sources/server_side.html
Hope it will help you.

Depending on what you want displayed for the "extra" page number, change what is echoed in the if statement:
//Loop Through Pages.
<?php
for ($i=1; $i <= $total_pages ; $i++)
{
if($total_pages > 8 && $i > 6 && $i < $total_pages) {
echo '..';
} else {
echo ''.$i.'';
}
}
?>

Related

How to create page numbers (for navigation) on a web page

I am writing PHP script to display data from the database (Mysql) on my webpage. I don't want all the information to display on a single page to avoid scrolling. However, I want to display only a few and then use page numbers to navigate to the rest. I managed to create the page numbers and yet still all the information is showing on a single page. Below is my code:
<?php
include('./includes/DB_Config.php');
$status = 1;
// Set number of Post per page for navigation
$post_per_page = 2;
if (isset($_GET['page']))
{
$startP = ($_GET['page'] - 1) * $post_per_page;
}
else
{
$startP = 0;
}
$post = mysqli_query ($mySQL_Conn, "SELECT * FROM BlogPost WHERE status = '$status'");
// Fetch Data or number of rows
$dataRw = mysqli_num_rows($post);
$pages = $dataRw / $post_per_page;
if ($dataRw == 0)
{
$_SESSION['NoPost'] = "No Post Found!";
}
else
{
unset($_SESSION['NoPost']);
//$pages = ceil($dataRw / $rows_per_page);
//$pages = array_slice($dataRw, $startP, $post_per_page);
while ($data = mysqli_fetch_array($post)) //Fetch data in array
{
//Assign data to variabes
$name = $data['blogger_Name'];
$postDate = $data['dateTime'];
$blogpost = $data['blog_message'];
$date = strtotime($postDate);
?>
<p> <span><?php echo $_SESSION['NoPost'] ; ?> </span></p>
<p> <span>By:</span><?php echo $name; ?> </p>
<p> <span>Posted On: </span> <?php echo date("j F Y", $date); ?> </p>
<p> <span>Post: </span><?php echo $blogpost; ?> </p>
<?php
}
}
?>
<hr>
<?php
for ($currentpage = 0; $currentpage < $pages; $currentpage++ )
{
?>
<span> <?php echo $currentpage + 1; ?> </span>
<?php
}
?>
What you are trying to accomplish is a very common pattern, and it's called pagination.
You can use LIMIT and OFFSET in your mysql queries to get only a certain subset of the data, and you can use this for basic pagination.
For example, if you want to display 50 results per page, and the user is on the third page, you set LIMIT to 50 and OFFSET to 2*50 (100), keep in mind the first page is an offset of 0 so we subtract the page by one.
You can use the following sql query to get a subset of data for a specific page.
"SELECT * FROM Users LIMIT $num_results OFFSET ".(($page_num-1)*$num_results);
You can get the total number of possible pages by getting the total row count from the Users table and dividing it by $num_results. A good idea might be to have your output script take a GET url query parameter that will be used as the page number.

Clicking on a link and should display the result on a same page

I am trying to filter details using a-z list, which I can do successfully.
But the problem I am facing is that when I want to display the result along with some pagination, it doesn't do exactly what I want it to do.
Here is my code:
<?php
session_start();
//what page are we currently on
if(!isset($_GET['page'])){
$page=1;
}
else {
$page=(int)$_GET['page'];
}
//select how many records to show per page
$limit=16;
//count how many rows
$total=$conn->query("SELECT COUNT(*) FROM `movie`")->fetchColumn();
//how many pages will be there
$pages=ceil($total/$limit);
if($page<1){
$page=1;//forcing page to be 1 if it is less then 1
}
else if($page>$pages){
$page=$pages;
}
//calculate the offset
$offset=($page-1)*$limit;
if(isset($_GET['word'])){
$qname=$_GET['word'];
}
else {
$qname='a';
}
$sql=$conn->prepare("SELECT * FROM `movie` WHERE `title` LIKE '$qname%' ORDER BY `movie_id` LIMIT $limit OFFSET $offset");
$sql->execute();
$sql->rowCount();
while($row=$sql->fetch(PDO::FETCH_ASSOC)){
$title=$row['title'];
$poster=$row['poster'];
echo '<li><a href="#">
<img src="'.$poster.'" />
<h2><strong>Watch '.$title.' Online</strong></h2>
</a>
</li>';
}
?>
Then somewhere in my html i have this pagination
<?php
$prev=$page-1;
$next=$page+1;
$previous="";
$nextr="";
if($page>1){
$previous='<li>«</span>';
}
if($page<$pages){
$nextr='<li>»</span>';
}
$numbers="";
if($pages>1){
for($i = max(1, $page - 5); $i <= min($page + 5, $pages); $i++){
if($i==$page){
$numbers.='<li><a class="active" href="?page='.$i.'">'.$i.'</a></span></li>';
}
else {
$numbers.='<li>'.$i.'</span></li>';
}
}
}
echo $previous;
echo $numbers;
echo $nextr;
?>
And my html :-
<div class="result"><h2>Browse By Words :- A | B</h2></div>
So when I click on link-a it displays the result and the url is like a-z.php?word=a and then when i try to paginate the url changes to a-z.php?page=2
So, how can I paginate the result after fetching it from the db?
I am looking for a way without ajax.

Check last row from phpmyadmin database with PHP

I am building a website and I want to add "previous" & "next" buttons to send the user to the previous or the next page. So i tried this:
where 'pid' is the 'post id' I did the same thing for 'next page' button
it worked... but it continues even if the page with that ID doesnt exist. im wondering if I could get some help with 'checking if current page is first row or last row.'.
Here's my code:
<?php
require('connect.php');
if(preg_match('/[^0-9]/i', $_REQUEST['pid'])) {
echo '<div style="margin:50px auto;" class="warning_msg">WARNING: !! Illegal character detected !! >> <b>'.$_REQUEST['pid'].'</b></div>';
} else {
$post_ = $dbh->query('SELECT * FROM `posts` WHERE `id`='.$dbh->quote($_REQUEST['pid']).'')->fetch();
echo '<div class="_header_ p_header_ disable_padding">
'.$post_['title'].'
<a href="?p=posts&pid='.($_REQUEST['pid']+1).'" class="next_page fa fa-hand-o-right" title="Next Post" ></a>
</div>
<div>'.$post_['article'].'</div>
<div class="_footer_">posted by <i>'.$post_['author'].'</i> on » '.date('M d Y H:m:i', strtotime($post_['post_time'])).'</div>';
}
?>
EDIT (SOLVED):
to find the first & last row i used a single query
$page = $dbh->query('SELECT MIN(id), MAX(id) FROM `posts`')->fetch();
and used like :
/* if current post id is equals to last id from posts */
if($_REQUEST['pid'] == $page[1]) { $next_page = $_REQUEST['pid'].'#';}
else { $next_page = ($_REQUEST['pid']+1); }
/* if current post id is equals to first id from posts */
if($_REQUEST['pid'] == $page[0]) { $prev_page = $_REQUEST['pid'].'#';}
else { $prev_page = ($_REQUEST['pid']-1); }
<?php
$lastpage = 10;
$ppage = isset($_REQUEST['pid']) && $_REQUEST['pid'] > 1 ? ($_REQUEST['pid']-1) : 0;
$npage = isset($_REQUEST['pid']) && $_REQUEST['pid'] < $lastpage ? ($_REQUEST['pid']+1) : $lastpage;
?>
Here i put a constant value 10 for last page.Instead of that you have to find outlast page id and replace that.Php pagination scripts are also available to find out first and last pages..

Paginating MySql Results

I have a table that pulls tickets from a MYSQL database and displays them to the user. This part works wonderfully! But, once the user gets 5-10 tickets, the page becomes long and ugly. I am wanting to paginate the responses automatically to show maybe 5 tickets per page and show the rest on following pages.
I am using Bootstrap and have the following for the display of the pagination. "Although I fear this is only pseudo code" I added id's to each main element.
<ul class="pager" id="pagerUL">
<li class="previous" id="previousUL">
← Previous
</li>
<li class="next" id="nextUL">
Next →
</li>
</ul>
Essentially the only code used to pull the database information on the page is:
<?php if(count($tickets) > 0) : ?>
<?php foreach ($tickets as $ticket): ?>
//table content
<?php endforeach ?>
<?php else : ?>
<tr>
<td colspan="7">No Tickets Created.</td>
</tr>
<?php endif; ?>
I thought we could add something to the <?php if(count($tickets) > 0) : ?> But honestly, I am not sure as I am not a expert at php and never even attempted or had the need to build pagination up until now. Any help, guidance, thoughts would be appreciated.
Pass the page number thru the URL and then grab it via php with $_GET.
$page = $_GET['page'];
$per_page = 10; // Define it as you please
$start = $page*$per_page;
$query = "SELECT * FROM table LIMIT ".$start.", ".$per_page;
$result = mysql_query($query);
$count = mysql_num_rows($result);
$i = 0;
for($i=0;$i<$count;$i++)
{
//echo out what you want
echo "";
}
$total_pages = ceil($count/$per_page);
for($i=0;$i<$total_pages;$i++)
{
if($page != $i)
{
echo "<a href='/page.php?page=".$i."'>".$i."</a>";
} else
{
echo $i;
}
}

Bizzare PHP behavior when moving from local (100% working) to hosted..some code working, some not

I've been building a website in PHP using a local install of MAMP on a MacBook Pro. Yesterday I finally managed to finish it with everything working so I decided to buy some webspace and host the files using exactly the same setup as the local install on MAMP (PHP 5.3, MySQL).
When I moved the files over and tested the site I get a really strange error. Most of the code is working, however, there are parts of the code that are broken, but in a very unusual way. I'll try my best to explain..
Note: This image probably shows off the error very well. I've blocked out some of the private content.
Image of the error
The first bit of code is this:
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;
$sql = "SELECT * FROM message,thumbsup_items WHERE message.id = thumbsup_items.name AND message.date BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW() ORDER BY votes_down DESC LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
$dest = "http://twitter-badges.s3.amazonaws.com/t_mini-b.png";
$dest2 = "images/fb-small.png";
$url="http://dfwm.ws";
while ($row = mysql_fetch_assoc($result))
{
?>
Which is 100% working on the local install, however on the hosted website it cuts off at:
$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;
$sql = "SELECT * FROM message,thumbsup_items WHERE message.id = thumbsup_items.name AND message.date BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW() ORDER BY votes_down DESC LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
$dest = "http://twitter-badges.s3.amazonaws.com/t_mini-b.png";
$dest2 = "images/fb-small.png";
$url="http://dfwm.ws";
while ($row = mysql_fetch_assoc($result))
{
?>
Meaning that the error must be to do with the < operator?. I'm unsure.
The next error is below:
<?
/****** build the pagination links ******/
// if not on page 1, don't show back links
if ($currentpage > 1) {
// get previous page num
$prevpage = $currentpage - 1;
// show < link to go back to 1 page
?>
<div id = "previous">
<?
echo " <a href='?currentpage=$prevpage'>«Previous</a> ";?>
</div>
<?
} // end if
// range of num links to show
$range = 2;
?>
<div id="pagination">
<?
// 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 "$x";
// if not current page...
} else {
// make it a link
echo " <a href='?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;
?>
</div>
<?
// echo forward link for next page
?><div id ="next"><?
echo " <a href='?currentpage=$nextpage'>Next »</a> ";?>
Which cuts off at:
1) {
I've come to the conclusion that if it was an error to do with the operators, as it has happened on both times, surely it would just not show anything, instead of coming out of the PHP tag and just displaying it as HTML? (the image shows this at the start of the question).
Would really appreciate some help as I've been racking my brain over it for hours.
Thanks
<? is the short open tag, which only works on PHP installs with the setting to enable them. I suggest you use the full <?php.
You're using short tags (<? instead of the full <?php opening declaration) which are advised against for exactly this reason: incompatibility with some servers.
Re-write any instances of <? to <?php and make sure you use <?php in the future.

Categories