PHP pagination function - php

public function paging($limit,$numRows,$page){
$allPages = ceil($numRows / $limit);
$start = ($page - 1) * $limit;
$querystring = "";
foreach ($_GET as $key => $value) {
if ($key != "page") $paginHTML .= "$key=$value&";
}
$paginHTML = "";
$paginHTML .= "Pages: ";
for ($i = 1; $i <= $allPages; $i++) {
$paginHTML .= "<a " . ($i == $page ? "class=\"selected\" " : "");
$paginHTML .= "href=\"?{$querystring}page=$i";
$paginHTML .= "\">$i</a> ";
}
return $paginHTML;
}
This is my pagination function for MVC pattern implementation.But this function has not displayed next and prev links.
I need to return HTML variable for pagination with previous and next link to controller.
I passed these variable to this function from controller.
$limit,$numRows,$page
How can I get next and prev links to above function.

I have added some conditions in the loop itself.
Hope they work.
Try the following:
<?php
public function paging($limit,$numRows,$page){
$allPages = ceil($numRows / $limit);
$start = ($page - 1) * $limit;
$querystring = "";
foreach ($_GET as $key => $value) {
if ($key != "page") $paginHTML .= "$key=$value&";
}
$paginHTML = "";
$paginHTML .= "Pages: ";
for ($i = 1; $i <= $allPages; $i++) {
if ($i>1) {
$prev = $i-1;
$paginHTML .= 'Previous';
}
$paginHTML .= "<a " . ($i == $page ? "class=\"selected\" " : "");
$paginHTML .= "href=\"?{$querystring}page=$i";
$paginHTML .= "\">$i</a> ";
if ($i<$allPages) {
$next = $i+1;
$paginHTML .= 'Next';
}
}
return $paginHTML;
}
?>

I'm using this pagination class like bellow inside my controller
case '' :
$page = isset ( $_REQUEST ['page'] ) ? $_REQUEST ['page'] : 1;
$limit = 5;
$allStudent = $student->getAllStudents();
$numRows = count($allStudent);
$start = ($page - 1) * $limit;
$students = $student->getStudentsWithLimit($start,$limit);
$paginHTML = $pagin->paging($limit,$numRows,$page);
$view->render('view/allStudent.php', array('allStudent' => $students,'pagin' => $paginHTML ));
break;
Get record function in Model class
public function getStudentsWithLimit($start,$limit){
$stmt = $this->db->con->query("SELECT * FROM student LIMIT $start, $limit");
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $results;
}

This should page with next and previous links with a max of 5 on either side of current page.
Pass in a function if you want the link formatted differently.
I've only given this very limited testing, and its been pulled out of a class, so you could replace some hard coded values in here with parameters of references to $this
function get_paging_links($result_count, callable $format_function=null)
{
if(!$format_function){
$format_function = function($url,$page,$qs){
$qs['page'] = $page;
return $url.'?'.http_build_query($qs);
};
}
$per_page = 5;
$total_pages = ceil($result_count / $per_page);
$return = [];
parse_str($_SERVER['QUERY_STRING'],$qs);
$url = $_SERVER['REQUEST_URI'];
//Remove existing query_string.
if($pos = strpos($url,'?')){
$url = substr($url,0,$pos);
}
$current_page = isset($qs['page']) ? $qs['page'] : 1;
$previous = $current_page -1;
if ($previous) {
$return['previous'] = $format_function($url,$previous,$qs);
}
for($i = max(1,$current_page-5); $i <= min($total_pages,$current_page+5); $i++) {
$return["$i"] = $format_function($url,$i,$qs);
}
$next_page = $current_page + 1;
if ($next_page < $total_pages){
$return['next'] = $format_function($url,$next_page,$qs);
}
return $return;
}

Related

How to make product diapason pagination in OpenCart 2.x?

I have OpenCart 2.1 and the website has such pagination (see screenshot)
default pagination
Here is the question: How to make like a product diapason pagination in OpenCart?
When I say the diapason pagination, I mean this (see screenshot please)
diapason pagination screenshot
Here is some code that is responsible for the formation of pagination.
<?php
class Pagination {
public $total = 0;
public $page = 1;
public $limit = 20;
public $num_links = 8;
public $url = '';
public $text_first = '|<';
public $text_last = '>|';
public $text_next = '>';
public $text_prev = '<';
public function render() {
$total = $this->total;
if ($this->page < 1) {
$page = 1;
} else {
$page = $this->page;
}
if (!(int)$this->limit) {
$limit = 10;
} else {
$limit = $this->limit;
}
$num_links = $this->num_links;
$num_pages = ceil($total / $limit);
$this->url = str_replace('%7Bpage%7D', '{page}', $this->url);
$output = '<ul class="pagination">';
if ($page > 1) {
$output .= '<li>' . $this->text_first . '</li>';
$output .= '<li>' . $this->text_prev . '</li>';
}
if ($num_pages > 1) {
if ($num_pages <= $num_links) {
$start = 1;
$end = $num_pages;
} else {
$start = $page - floor($num_links / 2);
$end = $page + floor($num_links / 2);
if ($start < 1) {
$end += abs($start) + 1;
$start = 1;
}
if ($end > $num_pages) {
$start -= ($end - $num_pages);
$end = $num_pages;
}
}
for ($i = $start; $i <= $end; $i++) {
if ($page == $i) {
$output .= '<li class="active"><span>' . $i . '</span></li>';
} else {
$output .= '<li>' . $i . '</li>';
}
}
}
if ($page < $num_pages) {
$output .= '<li>' . $this->text_next . '</li>';
$output .= '<li>' . $this->text_last . '</li>';
}
$output .= '</ul>';
if ($num_pages > 1) {
return $output;
} else {
return '';
}
}
}

codeigniter 3 customize pagination bootstrap

How can i customize my codeigniter links with bootstrap 4?
Im trying but i dont have luck with the a links.
thanks.
public function index($start=0)
{
if (!$this->session->userdata('user_id'))
{
redirect(base_url().'admin/login');
}
$this->load->model('M_Articulos');
$data['posts'] = $this->M_Articulos->select_posts(1, $start);
//paginacion
$this->load->library('pagination');
$config['base_url'] = base_url()."admin/index";
$config['total_rows'] = $this->M_Articulos->get_post_count();
$config['per_page'] = 1;
//paginacion estilos con bootstrap
$this->pagination->initialize($config);
$data['pages'] = $this->pagination->create_links(); //Links of pages
$this->load->view('admin/layouts/header');
$this->load->view('admin/modules/main', $data);
$this->load->view('admin/layouts/footer');
}
If you are using codeigniter-3,
check pagination library, if you are using default pagination library,
You need to make changes in create_links() function inside that as per your requirements.
Customizable code is here :
// Render the pages
if ($this->display_pages !== FALSE)
{
// Write the digit links
for ($loop = $start - 1; $loop <= $end; $loop++)
{
$i = ($this->use_page_numbers) ? $loop : ($loop * $this->per_page) - $this->per_page;
$attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, $loop);
if ($i >= $base_page)
{
if ($this->cur_page === $loop)
{
// Current page
$output .= $this->cur_tag_open.$loop.$this->cur_tag_close;
}
elseif ($i === $base_page)
{
// First page
$output .= $this->num_tag_open.'<a href="'.$first_url.'"'.$attributes.$this->_attr_rel('start').'>'
.$loop.'</a>'.$this->num_tag_close;
}
else
{
$append = $this->prefix.$i.$this->suffix;
$output .= $this->num_tag_open.'<a href="'.$base_url.$append.'"'.$attributes.'>'
.$loop.'</a>'.$this->num_tag_close;
}
}
}
}
// Render the "next" link
if ($this->next_link !== FALSE && $this->cur_page < $num_pages)
{
$i = ($this->use_page_numbers) ? $this->cur_page + 1 : $this->cur_page * $this->per_page;
$attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, $this->cur_page + 1);
$output .= $this->next_tag_open.'<a href="'.$base_url.$this->prefix.$i.$this->suffix.'"'.$attributes
.$this->_attr_rel('next').'>'.$this->next_link.'</a>'.$this->next_tag_close;
}
// Render the "Last" link
if ($this->last_link !== FALSE && ($this->cur_page + $this->num_links + ! $this->num_links) < $num_pages)
{
$i = ($this->use_page_numbers) ? $num_pages : ($num_pages * $this->per_page) - $this->per_page;
$attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, $num_pages);
$output .= $this->last_tag_open.'<a href="'.$base_url.$this->prefix.$i.$this->suffix.'"'.$attributes.'>'
.$this->last_link.'</a>'.$this->last_tag_close;
}

Bootstrap Pagination Questions

I have my website that I converted to bootstrap and all is well but pagers. The system my site uses now in functions.php
function pager($rpp, $count, $href, $opts = array())
{
global $language, $btit_settings;
$pager_type = "new";
if($btit_settings["fmhack_pager_type_select"] == "enabled")
$pager_type = $btit_settings["pager_type"];
if($pager_type == "new")
{
$pages = ($rpp == 0)?1:ceil($count / $rpp);
if(!isset($opts['lastpagedefault']))
$pagedefault = 1;
else
{
$pagedefault = floor(($count - 1) / $rpp);
if($pagedefault < 1)
$pagedefault = 1;
}
$pagename = 'pages';
if(isset($opts['pagename']))
{
$pagename = $opts['pagename'];
if(isset($_GET[$opts['pagename']]))
$page = max(1, intval($_GET[$opts['pagename']]));
else
$page = $pagedefault;
}
elseif(isset($_GET['pages']))
{
$page = max(1, intval(0 + $_GET['pages']));
if($page < 0)
$page = $pagedefault;
}
else
$page = $pagedefault;
$pager = '';
if($pages > 1)
{
$pager .= "\n".'<form name="change_page'.$pagename.'" method="post" action="index.php">'."\n".'<select class="drop_pager" name="pages" onchange="location=document.change_page'.$pagename.
'.pages.options[document.change_page'.$pagename.'.pages.selectedIndex].value" size="1">';
for($i = 1; $i <= $pages; $i++)
$pager .= "\n<option ".($i == $page?'selected="selected"':'')."value=\"$href$pagename=$i\">$i</option>";
$pager .= "\n</select>";
}
$mp = $pages; // - 1;
$begin = ($page > 3?($page < $pages - 2?$page - 2:$pages - 2):1);
$end = ($pages > $begin + 2?($begin + 2 < $pages?$begin + 2:$pages):$pages);
if($page > 1)
{
$pager .= "\n <ul class=\"pagination\"><li> «</li>></ul>";
$pager .= "\n<ul class=\"pagination\"><li>< </li></ul>";
}
if($count)
{
for($i = $begin; $i <= $end; $i++)
{
if($i != $page)
$pager .= "\n <ul class=\"pagination\"><li>$i</li></ul>";
else
$pager .= "\n <li class=\"active\">$i</li>";
}
if($page < $mp && $mp >= 1)
{
$pager .= "\n <ul class=\"pagination\"><li> ></li></ul>";
$pager .= "\n <ul class=\"pagination\"><li> »</li></ul>";
}
$pagertop = "$pager\n</form>";
$pagerbottom = str_replace("change_page", "change_page1", $pagertop)."\n";
}
else
{
$pagertop = "$pager\n</form>";
$pagerbottom = str_replace("change_page", "change_page1", $pagertop)."\n";
}
$start = ($page - 1) * $rpp;
if($pages < 2)
{
// only 1 page??? don't need pager ;)
$pagertop = '';
$pagerbottom = '';
}
return array(
$pagertop,
$pagerbottom,
"LIMIT $start,$rpp");
}
Is there a easy way or plugin i can use to incorporate bootstraps?
Here is sample from a page requests.php
list($pagertop,$pagerbottom,$limit) = pager(intval($btit_settings['req_page']),$count,$dir);
then sets it to a tag
$requeststpl->set("bottom_pager",$pagerbottom);
$requeststpl->set("top_pager",$pagertop);
which is then used as a tag to display it via the requests.tpl
<tag:bottom_pager />
<tag:top_pager />
I just want to have it so it looks like bootstrap style..... but comes out like this....
SAMPLE
SAMPLE2

Pagination not working because of two select statements

$today = date('D, d M, Y');
$sql = "SELECT * FROM table WHERE date = '$today'";
if ($_POST!="") {
$mydate = mysql_real_escape_string($_POST['datepicker']);
if ($mydate != "") {
$sql = "SELECT * FROM table WHERE date = '$mydate'";
}
}
$num_results_per_page = 8;
$num_page_links_per_page = 5;
$pg_param = "";
$result=mysql_query($sql);
$row = mysql_fetch_array($result);
pagination($sql, $num_results_per_page, $num_page_links_per_page, $pg_param);
if($pg_error == '')
{
if(mysql_num_rows($pg_result) > 0)
{
while($data = mysql_fetch_assoc($pg_result))
{
echo "";
}
echo "</br>". $pagination_output;
}
else
{
echo "No Data.";
}
}
else
{
echo $pg_error;
}
For the above code the pagination is not working properly. I am thinking that it is because of two select statements. It will be OK if we can combine those two. Any suggestions? How can I combine those two select statements?
Pagination is working correctly for select $today, but not working properly for select $mydate. For example if the user clicks page number two in select $mydate, its again going to select $today.
pagination.php
$pg_error = '';
$pg_result = '';
$pagination_output = '';
$max_pages = '';
$page_id = '';
$page_numbers_per_page = '';
$pg_user_param = '';
function pagination($sql, $num_results_per_page, $num_page_links_per_page, $pg_param)
{
global $pg_error, $pg_result, $max_pages, $page_id, $page_numbers_per_page, $pg_user_param;
$user_sql = $sql;
$page_numbers_per_page = $num_page_links_per_page;
$results_per_page = $num_results_per_page;
$pg_user_param = $pg_param;
$all_results = mysql_query($user_sql);
if($all_results)
{
if(empty($all_results))
{
$total_results = 0;
}
else
{
$total_results = mysql_num_rows($all_results);
}
$max_pages = ceil($total_results / $results_per_page);
if(isset($_GET['page_id']))
{
$page_id = (int) $_GET['page_id'];
if($page_id > $max_pages || empty($page_id))
{
$page_id = 1;
}
}
else
{
$page_id = 1;
}
$page_id_temp = ($page_id - 1) * $results_per_page;
$sql_offset = $page_id_temp;
$user_sql .= " limit $sql_offset, $results_per_page";
$pg_result = mysql_query($user_sql);
Create_Links();
}
else
{
$pg_error = 'Error with the sql query you entered: '.mysql_error();
}
}
function Create_Links()
{
global $pagination_output, $max_pages, $page_id, $page_numbers_per_page, $pg_user_param;
$pg_page_name = htmlspecialchars($_SERVER['PHP_SELF'] );
if($max_pages > 1)
{
if($page_id > 1)
{
$first_link = 'First ';
}
if($page_id < $max_pages)
{
$last_link = 'Last ';
}
$pre_id = $page_id - 1;
if($pre_id != 0)
{
$pre_link = 'Previous ';
}
$next_id = $page_id + 1;
if($next_id <= $max_pages)
{
$next_link = 'Next ';
}
if($page_id >= $page_numbers_per_page)
{
$start_point = ($page_id - $page_numbers_per_page) + 2;
}
else
{
$start_point = 1;
}
$loop_num = ($start_point + $page_numbers_per_page) - 1;
if($loop_num > $max_pages)
{
$loop_num = $max_pages;
}
$pagination_output = '<div class="pagination"> ';
$pagination_output .= $first_link;
$pagination_output .= $pre_link;
for($i = $start_point; $i <= $loop_num; $i++)
{
if($i == $page_id)
{
$pagination_output .= '<a class="current">'.$i.'</a> ';
}
else
{
$pagination_output .= ''.$i.' ';
}
}
$pagination_output .= $next_link;
$pagination_output .= $last_link;
$pagination_output .= '</div><br />';
}
}
?>
If pagination is working for "$today" then it must be the POST input value - are you making sure you're getting a proper date that mysql can understand?
the format should basically match what's in "$today".
I'd imagine that the second click is not POSTing myDate to the next page. The next page then sees nothing in POST and uses today.
To avoid this you could also check for GETs of the datepicker and then pass myDate using GET.
Edit: Clarification on updating the code to use GET
The check on mydate should be changed to something like:
if ($_REQUEST!="") {
$mydate = mysql_real_escape_string($_REQUEST['datepicker']);
if ($mydate != "") {
$sql = "SELECT * FROM table WHERE date = '$mydate'";
}
}
Which means that if the datepicker is from a GET request we still grab it.
Create_Links() should be changed to add "&datepicker=$mydate" (note that you will need to pass in $myDate to ths function.

PHP question pagination

How would I do so that the page I'm on won't be clickable?
$page = (isset($_GET['page']) && is_numeric($_GET['page']) ? (int) $_GET['page'] : 1);
$limit = ($page - 1) * 15;
$sql = mysql_query("SELECT * FROM log LIMIT $limit, 15");
$totalres = mysql_result(mysql_query("SELECT COUNT(id) AS tot FROM log"),0);
$totalpages = ceil($totalres / 15);
for ($i = 1; $i <= $totalpages; $i++) {
$pagination .= "$i ";
}
<p><?php echo $pagination ?></p>
if ($i == $page)
$pagination .= "$i ";
else
$pagination .= "$i ";
Just need to modify the for loop to check what the current page is.
for ($i = 1; $i <= $totalpages; $i++)
{
if ($i != $page)
$pagination .= "$i ";
else
$pagination .= " " . $i . " ";
}
With an if inside the for,
if ( $i != $page) {
//Your code.
}
else
{
//Same page.
$pagination .= " " . $page . " "
}
#RedBlueThing Has soon has I saw your post I got it to work, although I got the idea from a different stackoverflow question with a little modifying of the code.
<?php
echo "<section>";
$link = mysqli_connect("localhost", "root", "root", "user_db");
$page = (isset($_GET['page']) && is_numeric($_GET['page']) ? (int) $_GET['page'] : 1);
$offset = 4;
$x = 5;
$limit = ($page - 1) * $offset;
$sql = mysqli_query($link,"SELECT * FROM cfp_blogs;");
$totalres = mysqli_num_rows($sql);
$totalpages = ceil($totalres / $offset);
$stmt = mysqli_query($link, "SELECT * FROM blogs LIMIT $limit, $offset;");
if($stmt->num_rows > 0){
while($obj = mysqli_fetch_object($stmt)) {
echo "<h1>$obj->title</h1>";
echo "<p>$obj->content</p>";
$stmt2 = $link->query("SELECT COUNT(id) AS Tot FROM blogs");
if($stmt2->num_rows > 0){
while ($obj2 = $stmt2->fetch_object()){
echo "<p>($obj2->Tot)</p>";
}
}
else
echo "<p>(0)</p>";
$stmt2->close();
}
}
else {
echo "<section class='error'><h1>There was a problem with the database.</h1></section>";
}
mysqli_free_result($stmt);
for ($i = $page - $x; $i < $page; $i++)
{
if ($i >= 1) {
$pagination .= "$i ";
}
}
$pagination .= " " . $i . " ";
for ($i = $page + 1; $i <= $page + $x; $i++)
{
if ($i <= $totalpages) {
$pagination .= "$i ";
}
}
/*for ($i = 1; $i <= $totalpages; $i++)
{
if ($i != $page){
$pagination .= "$i ";
}
else{
$pagination .= " " . $i . " ";
}
}*/
mysqli_close($link);
echo $pagination;
echo "</section>";
?>
The only thing I couldn't get was having a "next" or "previous" button. If anyone is up to the task of adding on those buttons, give it a shot. Other wise..... Enjoy..... :) This is my way of giving back to the stackoverflow community for helping me.

Categories