Function at a theme for wordpress, Helping to edit something - php

I have been installing a Wordpress Theme, the theme has a custom navigation function.
It shows a page navigation at archive, categories but doesn't show at tag.
This is the function from functions.php
<?php function wp_pagenavi($before = '', $after = '', $prelabel = '', $nxtlabel = '', $pages_to_show = 5, $always_show = false) {
global $request, $posts_per_page, $wpdb, $paged;
if(empty($prelabel)) { $prelabel = '<strong>«</strong>';
} if(empty($nxtlabel)) {
$nxtlabel = '<strong>»</strong>';
} $half_pages_to_show = round($pages_to_show/2);
if (!is_single()) {
if(!is_category()) {
preg_match('#FROM\s(.*)\sORDER BY#siU', $request, $matches); } else {
preg_match('#FROM\s(.*)\sGROUP BY#siU', $request, $matches); }
$fromwhere = $matches[1];
$numposts = $wpdb->get_var("SELECT COUNT(DISTINCT ID) FROM $fromwhere");
$max_page = ceil($numposts /$posts_per_page);
if(empty($paged)) {
$paged = 1;
}
if($max_page > 1 || $always_show) {
echo "$before <div class='Nav'><span>Pages ($max_page): </span>"; if ($paged >= ($pages_to_show-1)) {
echo '« First ... '; }
previous_posts_link($prelabel);
for($i = $paged - $half_pages_to_show; $i <= $paged + $half_pages_to_show; $i++) { if ($i >= 1 && $i <= $max_page) { if($i == $paged) {
echo "<strong class='on'>$i</strong>";
} else {
echo ' '.$i.' '; }
}
}
next_posts_link($nxtlabel, $max_page);
if (($paged+$half_pages_to_show) < ($max_page)) {
echo ' ... Last »'; }
echo "</div> $after";
}
}
}
?>
I hope anyone helping with that function to show page navigation at tag, thanks.

It's doing the wrong match. Change if(!is_category()) into if(!is_category()&&!is_tag())

Related

Need Pagination Script For MVC

I have Custom MVC and stuck on Pagination. Please give me code my MVC Structure is here.
index->controller->model->back-to-controller->then-view.
Please help me out to create pagination to fit that MVC.
My Controller:
class Posts extends Controller{
public function __construct(){
$this->postModel = $this->model('Post');
}
public function index(){
$allpost = $this->postModel->getAllPosts();
$data = [
'posts' => $allpost,
];
$this->view('jobs/index', $data);}}
here is my Model:
class Post {
private $db;
public function __construct(){
$this->db = new Database;
}
public function getAllPosts(){
$this->db->query('select * from posts where active = 0 ');
return $this->db->resultSet();
}
here is my View:
<?php foreach($data['allposts'] as $posts) : ?>
<div class="jobContent">
<div class="jobTitle">
<h5><?= $posts->title; ?></h5>
</div>
<div class="cName">
<?= $posts->des; ?>
</div>
</div>
<?php endforeach ;?>
Use Datatables, it gives you the pagination and search functionality.
for example, you have your table like <table id='sth'> </table>, just add the following CDNs:
<link href="https://cdn.datatables.net/1.10.18/css/dataTables.bootstrap.min.css" rel="stylesheet" type="text/css">
Also :
<script src="https://cdn.datatables.net/1.10.18/js/jquery.dataTables.min.js" type="text/javascript"></script>
and <script src="https://cdn.datatables.net/1.10.18/js/dataTables.bootstrap.min.js" type="text/javascript"></script>
Then after that add this:
<script>
$(document).ready(function () {
$('#sth').DataTable();
});
</script>
<?php
class Pagination{
protected $baseURL = '';
protected $totalRows = '';
protected $perPage = 10;
protected $numLinks = 2;
protected $currentPage = 0;
protected $firstLink = 'First';
protected $nextLink = 'Next »';
protected $prevLink = '« Prev';
protected $lastLink = 'Last';
protected $fullTagOpen = '<div class="pagination">';
protected $fullTagClose = '</div>';
protected $firstTagOpen = '';
protected $firstTagClose = ' ';
protected $lastTagOpen = ' ';
protected $lastTagClose = '';
protected $curTagOpen = ' <b>';
protected $curTagClose = '</b>';
protected $nextTagOpen = ' ';
protected $nextTagClose = ' ';
protected $prevTagOpen = ' ';
protected $prevTagClose = '';
protected $numTagOpen = ' ';
protected $numTagClose = '';
protected $showCount = true;
protected $currentOffset= 0;
protected $queryStringSegment = 'page';
function __construct($params = array()){
if (count($params) > 0){
$this->initialize($params);
}
}
function initialize($params = array()){
if (count($params) > 0){
foreach ($params as $key => $val){
if (isset($this->$key)){
$this->$key = $val;
}
}
}
}
/**
* Generate the pagination links
*/
function createLinks(){
// If total number of rows is zero, do not need to continue
if ($this->totalRows == 0 OR $this->perPage == 0){
return '';
}
// Calculate the total number of pages
$numPages = ceil($this->totalRows / $this->perPage);
// Is there only one page? will not need to continue
if ($numPages == 1){
if ($this->showCount){
$info = 'Showing : ' . $this->totalRows;
return $info;
}else{
return '';
}
}
// Determine query string
$query_string_sep = (strpos($this->baseURL, '?') === FALSE) ? '?page=' : '&page=';
$this->baseURL = $this->baseURL.$query_string_sep;
// Determine the current page
$this->currentPage = isset($_GET[$this->queryStringSegment])?$_GET[$this->queryStringSegment]:0;
if (!is_numeric($this->currentPage) || $this->currentPage == 0){
$this->currentPage = 1;
}
// Links content string variable
$output = '';
// Showing links notification
if ($this->showCount){
$currentOffset = ($this->currentPage > 1)?($this->currentPage - 1)*$this->perPage:$this->currentPage;
$info = 'Showing ' . $currentOffset . ' to ' ;
if( ($currentOffset + $this->perPage) <= $this->totalRows )
$info .= $this->currentPage * $this->perPage;
else
$info .= $this->totalRows;
$info .= ' of ' . $this->totalRows . ' | ';
$output .= $info;
}
$this->numLinks = (int)$this->numLinks;
// Is the page number beyond the result range? the last page will show
if($this->currentPage > $this->totalRows){
$this->currentPage = $numPages;
}
$uriPageNum = $this->currentPage;
// Calculate the start and end numbers.
$start = (($this->currentPage - $this->numLinks) > 0) ? $this->currentPage - ($this->numLinks - 1) : 1;
$end = (($this->currentPage + $this->numLinks) < $numPages) ? $this->currentPage + $this->numLinks : $numPages;
// Render the "First" link
if($this->currentPage > $this->numLinks){
$firstPageURL = str_replace($query_string_sep,'',$this->baseURL);
$output .= $this->firstTagOpen.''.$this->firstLink.''.$this->firstTagClose;
}
// Render the "previous" link
if($this->currentPage != 1){
$i = ($uriPageNum - 1);
if($i == 0) $i = '';
$output .= $this->prevTagOpen.''.$this->prevLink.''.$this->prevTagClose;
}
// Write the digit links
for($loop = $start -1; $loop <= $end; $loop++){
$i = $loop;
if($i >= 1){
if($this->currentPage == $loop){
$output .= $this->curTagOpen.$loop.$this->curTagClose;
}else{
$output .= $this->numTagOpen.''.$loop.''.$this->numTagClose;
}
}
}
// Render the "next" link
if($this->currentPage < $numPages){
$i = ($this->currentPage + 1);
$output .= $this->nextTagOpen.''.$this->nextLink.''.$this->nextTagClose;
}
// Render the "Last" link
if(($this->currentPage + $this->numLinks) < $numPages){
$i = $numPages;
$output .= $this->lastTagOpen.''.$this->lastLink.''.$this->lastTagClose;
}
// Remove double slashes
$output = preg_replace("#([^:])//+#", "\\1/", $output);
// Add the wrapper HTML if exists
$output = $this->fullTagOpen.$output.$this->fullTagClose;
return $output;
}
}
and here code to index:
$baseURL = 'http://example.com/php_pagination/index.php';
$limit = 5;
$offset = !empty($_GET['page'])?(($_GET['page']-1)*$limit):0;
foreach($$data['allcount'] as $allcount){
$rowCount = $allcount->count;
}
$pagConfig = array(
'baseURL' => $baseURL,
'totalRows'=>$rowCount,
'perPage'=>$limit
);
$pagination = new Pagination($pagConfig);
<div class="post-list">
<?php foreach($data['alljobs'] as $alljobs){
<?php echo $alljobs->job_title; ?>
} ?>
<div class="list-item">
<?php echo $row["title"]; ?>
</div>
<?php } ?>
</div>
<?php echo $pagination->createLinks(); ?>
<?php } ?>enter code here
by using that code i can get the pagination but record are not changing its shows same in all pages.

PHP PDO Pagination not refreshed

im quite new to PHP and im trying to make a pagination, the code works! but i need to click on the button twice to make the page refreshed/change. how do i fix this?
view/main/user/userlist.php
<?php
$_SESSION['pagelim'] = 10;
$_SESSION['page'] = $_GET['halaman'];
if ($_SESSION['page'] == '') {
$_SESSION['pos'] = 0;
$_SESSION['page'] = 1;
} else {
$_SESSION['pos'] = ($_SESSION['page']- 1) * $_SESSION['pagelim'];
}
$itemcount = listpetugas::getlisted();
$pagecount = ceil(listpetugas::getlisted()/$_SESSION['pagelim']);
for ($i=1;$i<=$pagecount;$i++)
{ ?>
<?php
if ($i!=$pagecount){
echo " <ul class='pagination'><li><a href='?controller=main&action=userlist&halaman=$i' onclick='myFunction()'>$i</a></li></ul>";?>
<?php }
else{
echo "$i";
} ?>
<?php } ?>
model/userdb.php
public static function listemup()
{
if ($_SESSION['pos'] =='' && $_SESSION['pagelim'])
{
$pos = 0;
$lim = 10;
}
else {
$pos = $_SESSION['pos'];
$lim = $_SESSION['pagelim'];
}
$list = [];
$db = FirstFire::StartConnection();
$req = $db->query("SELECT * FROM randomity LIMIT $pos,$lim");
$rowcount = $req->rowCount();
foreach ($req->fetchAll() as $post) {
$list[] = new listpetugas($post['name'],$post['email'],$post['adress'],$post['wow']);
}
return $list;
}
JS
<script>
function myFunction() {
location.reload();
}
</script>
sorry for the messy code.

Pagination with $this->db->query() and $this->db->limit()

I tried the following code for pagination but it not works for me it not shows 10 records per page it shows all records on the single page and again same number of records shows on the next page my code in controller
<?php
class Classified_detail extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('Jobseekermodel','',TRUE);
//$this->load->database($config);
//$secound_db= $this->load->database('classified_db', TRUE);
//$CI = &get_instance();
$this->db2 = $this->load->database('classified_db', TRUE); //doolaly
$this->load->model('Emailmodel','',TRUE);
$this->load->model('Bookmodel','',TRUE);
$this->load->model('Consultantmodel','',TRUE);
$this->load->model('Openingmodel','',TRUE);
//$this->load->model('classified/Mobile_model','',TRUE);
$this->load->model('classified/classified_ad','',TRUE);
$this->load->model('classified/create_ad','',TRUE);
$this->load->model('Commfuncmodel','',TRUE);
$this->lang->load('message', 'english');
$this->lang->load('mail', 'english');
$this->load->library('form_validation');
if (session_id() == "") session_start();
}
/***********************Start of Function For Showing list of ebooks from database **********************************/
function index($msg=NULL)
{
$this->Commfuncmodel->checkJobseekerLogin();
//******My expired ads*******/
//post ad history
$_SESSION["ex_ad_paging"] = PER_PAGE_RECORDS;
$today = date('Y-m-d');
$qry ="select AM.Ad_Title as Title,AM.Advertizement_Text as Description,AM.Price,AMP.Expiry_Date
from ad_mobile_phones AM inner join ad_mobilephone_plan_mapping AMP on
AM.Ad_ID=AMP.Ad_ID
where AM.Created_By='".$_SESSION['jobseeker_id']."' and AMP.Expiry_Date <'".$today."'
UNION
select A.Title,A.Description,A.Price,B.Expiry_Date from ad_vehicle A inner join ad_vehicle_plan_mapping B
on A.Ad_ID = B.Ad_ID where A.Created_By ='".$_SESSION['jobseeker_id']."' and B.Expiry_Date <'".$today."'";
$query=$this->db->query($qry);
$ex_ed_count=$query->num_rows();
$ex_ad_data=$query->result_array();
/******************Start of Pagination****************/
$segments = array('classified/classified_detail','index/my_ex_ads');
$url_name=site_url($segments);
$ex_ed_count = count($ex_ad_data);
$per_page_records=((#$_SESSION["ex_ad_paging"]=="All")?$ex_ed_count:#$_SESSION["ex_ad_paging"]);
$expagination=$this->Commfuncmodel->pagination_a($ex_ed_count,$this->uri->segment(5),$per_page_records,$url_name,"1","EXAD");
/******************End Pagination******************/
if($this->uri->segment(4)== "my_ex_ads")
{
$page_no=(int)$this->uri->segment(5);
if( empty($page_no) || ( $page_no <1 ) )
$nextrecord = 0 ;
else
$nextrecord = ($page_no-1) * #$_SESSION["ex_ad_paging"] ;
}
if($_SESSION["ex_ad_paging"]!="All")
{
$limit_start=$nextrecord;
$limit_end=$_SESSION["ex_ad_paging"];
}
else
{
$limit_start=0;
$limit_end=$ex_ed_count;
}
$qry ="select AM.Ad_Title as Title,AM.Advertizement_Text as Description,AM.Price,AMP.Expiry_Date
from ad_mobile_phones AM inner join ad_mobilephone_plan_mapping AMP on
AM.Ad_ID=AMP.Ad_ID where AM.Created_By='".$_SESSION['jobseeker_id']."' and AMP.Expiry_Date <'".$today."'
UNION
select A.Title,A.Description,A.Price,B.Expiry_Date from ad_vehicle A inner join ad_vehicle_plan_mapping B
on A.Ad_ID = B.Ad_ID where A.Created_By ='".$_SESSION['jobseeker_id']."' and B.Expiry_Date <'".$today."'";
//$this->db->limit(#$limit_end,#$limit_start);
//var_dump($limit_end);
//var_dump($limit_start);
$query=$this->db->query($qry);
$this->db->limit(#$limit_end,#$limit_start);
//var_dump($query);
$my_ad_data=$query->result_array();
//old data
//$this->db2->where('Expiry_Date' < $date);
// $this->db2->limit(#$limit_end,#$limit_start);
//$query=$this->db2->get(ad_mobilephone_plan_mapping);
// $my_ad_data=$query->result_array();
//follw up
$i=0;
if($query->num_rows()>0)
{
foreach($my_ad_data as $item => $v)
{
//$my_ad_data[$i]['applied_js']="y";
//follow up mail sent
//$this->db2->where("Ad_ID",$my_ad_data[$i]['Ad_ID']);
//$this->db2->where('Expiry_Date' < $date);
//$query=$this->db2->get(ad_mobilephone_plan_mapping);
//var_dump($fquery);
//$my_ad_data[$i]['count'] = $fquery->num_rows();
$qry ="select AM.Ad_Title as Title,AM.Advertizement_Text as Description,AM.Price,AMP.Expiry_Date
from ad_mobile_phones AM inner join ad_mobilephone_plan_mapping AMP on
AM.Ad_ID=AMP.Ad_ID where AM.Created_By='".$_SESSION['jobseeker_id']."' and AMP.Expiry_Date <'".$today."'
UNION
select A.Title,A.Description,A.Price,B.Expiry_Date from ad_vehicle A inner join ad_vehicle_plan_mapping B
on A.Ad_ID = B.Ad_ID where A.Created_By ='".$_SESSION['jobseeker_id']."' and B.Expiry_Date <'".$today."'";
$fquery = $this->db->query($qry);
//var_dump($fquery);
//var_dump($my_ad_data[$i]['count']);
$my_ad_data[$i]['count'] = $fquery->num_rows();
if($fquery->num_rows() < 2)
{
$my_ad_data[$i]['sent_follow']="y";
}
$oid = substr($my_ad_data[$i]['opening_id'],-9);
$my_ad_data[$i]['oid'] = substr($oid,0,-1);
$i++;
}
}
$data['acc'] = 'acc';
$data['page_no'] = $page_no;
$data['ex_ad_data'] = $my_ad_data;
$data['ex_ed_count'] = $ex_ed_count;
$data['expagination'] =$expagination;
$data['nextrecord'] = $nextrecord;
$data['msg_display'] =$msg_display;
$data['view_file'] = 'classified/account';
if($this->uri->segment(4)=="h")
{
$data['ajax'] = 1;
$this->load->view('account/historylist',$data);
}
else if($this->uri->segment(4)=="my_ads")
{
$data['ajax'] = 1;
$this->load->view('classified/classified_ads',$data);
}
else if($this->uri->segment(4)=="my_ex_ads")
{
$data['ajax'] = 1;
$this->load->view('account/expired_ads',$data);
}
else if($this->uri->segment(4)=="job")
{
$data['ajax'] = 1;
$this->load->view('account/joblist',$data);
}
else
{
$this->load->view('classified/classified_layout',$data);
}
}
Please help me and thanks in advance
Model Commfuncmodel.php
<?php
class Commfuncmodel extends CI_Model
{
function __construct()
{
parent::__construct();
//$this->load->model('Adminmodel','',TRUE);
}
function getcounter($tblnm,$id,$val)
{
$this->db->select('counter');
$this->db->where($id,$val);
$query = $this->db->get($tblnm);
$data=$query->result_array();
return $data[0];
}
function setcounter($tblnm,$id,$val)
{
$cnt = $this->getcounter($tblnm,$id,$val);
$data['counter'] = $cnt['counter'] + 1;
$this->db->where($id, $val);
$this->db->update($tblnm,$data);
return true;
}
/**************************PAGINATION FUNCTION START*************************************/
function pagination($total_rec, $current_page=0, $perPage, $url_name)
{
$pagination = "" ;
//echo $current_page;
// if total records are less than per page record then dont show pagination
if($total_rec<= $perPage)
{
return ;
}
// Retrieve Current Page number
if($current_page < 0 || $current_page==0)
{
$p = 1 ;
}
else
{
$p = $current_page ;
}
// Calculate Total Pages
$total_pages = (int)($total_rec/$perPage) ;
if( ($total_rec%$perPage) > 0 )
{
$total_pages++ ;
}
//echo "total pages ".$total_pages;
//echo "p is ".$p;
// To show pagination
if($total_pages >= 1)
{
$pagination .= '<ul class="pagination" style="margin-left:150px;">';
//$pagination .= "<br>Showing Page ".$p." of ".$total_pages."<br>";
// FIRST & PRIV LINKS
if($p>1)
{
//$pagination .= "<a href='".$url_name."/1'>"."First"."</a> " ;
$pagination .= "<li><a style='color: #000;' href='".$url_name."/". ($p-1) ."'>"." Prev"."</a></li>" ;
}
// Middle links..
if( ($p%BEFORE_AFTER_NO) == 0)
{
if( ($total_pages - $p) > BEFORE_AFTER_NO)
{
$start = $p-BEFORE_AFTER_NO ? $p-BEFORE_AFTER_NO:1 ;
}
else
{
$start = $total_pages - TOTAL_PAGINATION_NO;
if($start <= 0)
{
$start = 1 ;
}
}
$end = $p+BEFORE_AFTER_NO ;
}
else
{
if($p > 9)
{
if( ($total_pages - $p) > BEFORE_AFTER_NO)
{
$start = $p - BEFORE_AFTER_NO ;
}
else
{
$start = $total_pages - TOTAL_PAGINATION_NO;
}
$end = $p + BEFORE_AFTER_NO ;
}
else
{
$start = 1 ;
$end = TOTAL_PAGINATION_NO;
}
}
for($i=$start; $i<=$end && $i<=$total_pages;$i++)
{
if($i==$p)
{
$pagination .= '<li class="active">'.$i.'</li>' ;
}
else
{
$pagination .= "<li><a style='color: #000;' href='".$url_name."/". $i ."'>".$i."</a></li>" ;
}
}
// NEXT & LAST links
if($p>=1 && $p<$total_pages)
{
$pagination .= "<li ><a style='color: #000;' href='".$url_name ."/". ($p+1) ."'>"."Next"."</a></li>" ;
//$pagination .= "<a href='".$url_name ."/$total_pages'>"."Last"."</a> " ;
}
} // if($total_pages>1) end.
$pagination .='</ul>' ;
return ($pagination) ;
}
function pagination_a($total_rec, $current_page=0, $perPage, $url_name,$ajaxflag=NULL,$d)
{
$pagination = "" ;
// if total records are less than per page record then dont show pagination
if($total_rec<= $perPage)
{
return ;
}
// Retrieve Current Page number
if($current_page<0 || $current_page==0)
{
$p = 1 ;
}
else
{
$p = $current_page ;
}
// Calculate Total Pages
$total_pages = (int)($total_rec/$perPage) ;
if( ($total_rec%$perPage) > 0 )
{
$total_pages++ ;
}
// To show pagination
if($total_pages >= 1)
{
$pagination .= '<ul class="pagination" style="margin-left:227px;">';
// FIRST & PRIV LINKS
if($p>1)
{
if($ajaxflag)
{
//$pagination .= "<a href=javascript:ajaxPagination('".$url_name."/1')>".lang("FIRST")."</a> " ;
$pagination .= "<li><a href=javascript:ajaxPagination('".$url_name."/". ($p-1) ."/".$d."')>"."PREV"."</a></li>" ;
}
else
{
//$pagination .= "<a href='".$url_name."/1'>".lang("FIRST")."</a> " ;
$pagination .= "<li><a href='".$url_name."/". ($p-1) ."'>"."PREV"."</a></li>" ;
}
}
// Middle links..
//echo $total_pages;
if( ($p%BEFORE_AFTER_NO) == 0)
{
if( ($total_pages - $p) > BEFORE_AFTER_NO)
{
$start = $p-BEFORE_AFTER_NO ? $p-BEFORE_AFTER_NO:1 ;
}
else
{
$start = $total_pages - TOTAL_PAGINATION_NO;
if($start <= 0)
{
$start = 1 ;
}
}
$end = $p+BEFORE_AFTER_NO ;
}
else
{
if($p > 9)
{
if( ($total_pages - $p) > BEFORE_AFTER_NO)
{
$start = $p - BEFORE_AFTER_NO ;
}
else
{
$start = $total_pages - TOTAL_PAGINATION_NO;
}
$end = $p + BEFORE_AFTER_NO ;
}
else
{
$start = 1 ;
$end = TOTAL_PAGINATION_NO;
}
}
for($i=$start; $i<=$end && $i<=$total_pages;$i++)
{
if($i==$p)
{
$pagination .= '<li class="active"><a class="page-links" id="current">'.$i.'</a></li> ' ;
}
else
{
if($ajaxflag)
$pagination .= "<li><a href=javascript:ajaxPagination('".$url_name."/". $i ."/".$d."')>$i</a></li>" ;
else
$pagination .= "<li><a href='".$url_name."/". $i ."'>$i</a></li>" ;
}
}
// NEXT & LAST links
if($p>=1 && $p <$total_pages)
{
if($ajaxflag)
{
$pagination .= "<li><a href=javascript:ajaxPagination('".$url_name ."/". ($p+1) ."/".$d."')>"."NEXT"."</a></li>";
//$pagination .= "<a href=javascript:ajaxPagination('".$url_name ."/$total_pages')>".lang("LAST")."</a> " ;
}
else
{
$pagination .= "<li><a href='".$url_name ."/". ($p+1) ."'>"."NEXT"."</a></li>";
//$pagination .= "<a href='".$url_name ."/$total_pages'>".lang("LAST")."</a> " ;
}
}
} // if($total_pages>1) end.
$pagination .='</ul>';
//echo $pagination;
return ($pagination) ;
}
}
?>

PHP return an pagination object and displaying the links when called

I have this pagination class which I converted from a normal procedural function to a class since I started learning OOP. In the old procedural way, the function worked fine but I can't get this new class version to display on the screen
class Pagination {
public function __construct() {
}
/**
* This function is called whenever the there are several records to be displayed in the table
* This saves the page extending further down the page creating a long list of results
* when all the results can be spread across multiple pages
*/
public function pagination_one($total_pages, $page, $webpage) {
// Maximum number of links per page. If exceeded, google style pagination is generated
$max_links = 6;
$h=1;
if($page>$max_links) {
$h=(($h+$page)-$max_links);
}
if($page>=1) {
$max_links = $max_links+($page-1);
}
if($max_links>$total_pages) {
$max_links=$total_pages+1;
}
echo '<div class="page_numbers">
<ul>';
if($page>"1") {
echo '<li class="current">First</li>
<li class="current">Prev</li> ';
}
if($total_pages!=1) {
for ($i=$h;$i<$max_links;$i++) {
if($i==$page) {
echo '<li><a class="current">'.$i.'</a></li>';
}
else
{
echo '<li>'.$i.' </li>';
}
}
}
if(($page >="1")&&($page!=$total_pages)) {
echo '<li class="current">Next</li>
<li class="current">Last</li>';
}
echo '</ul> </div>';
}
and elsewhere in another class I want to create a new instance of that class and pass the method in the return along with some parameters
public function paging() {
if($this->getcount != 0) {
$this->paging = new Pagination();
return $this->paging->pagination_one($this->total_pages, $this->page, 'news');
}
}
When I try I var_dump() it comes up as NULL where I expect to see some pagination on the screen.
What have i got to change to be able to display the pagination? Do I have to created some variables in the Pagination class for $total_pages, $page and $webpage and initialise them in the constructor and remove them from the pagination_one method?
You do
return $this->paging->pagination_one...
when you are not returning anything in pagination_one -method, hence null.
I fixed it myself by removing the private variables in the class and changing the constructor.
The class now looks like this
class Pagination {
public function __construct($total_pages, $page, $webpage) {
$this->total_pages = $total_pages;
$this->page = $page;
$this->webpage = $webpage;
}
/**
* This function is called whenever the there are several records to be displayed in the table
* This saves the page extending further down the page creating a long list of results
* when all the results can be spread across multiple pages
*/
public function pagination_one() {
// Maximum number of links per page. If exceeded, google style pagination is generated
$max_links = 6;
$h = 1;
if($this->page > $max_links) {
$h=(($h + $this->page) - $max_links);
}
if($this->page >= 1) {
$max_links = $max_links + ($this->page - 1);
}
if($max_links > $this->total_pages) {
$max_links = $this->total_pages + 1;
}
$paging = '';
$paging .= '<div class="page_numbers">
<ul>';
if($this->page > "1") {
$paging .= '<li class="current">First</li>
<li class="current">Prev</li> ';
}
if($this->total_pages != 1) {
for ($i=$h; $i < $max_links; $i++) {
if($i == $this->page) {
$paging .= '<li><a class="current">'.$i.'</a></li>';
}
else {
$paging .= '<li>'.$i.' </li>';
}
}
}
if(($this->page >= "1" ) && ($this->page != $this->total_pages)) {
$paging .= '<li class="current">Next</li>
<li class="current">Last</li>';
}
$paging .= '</ul> </div>';
return $paging;
}
}
function pagination($sql_total_row, $post_per_page,$current_page=1, $url='', $lasturl = '', $parameter ='paging') {
$number_page = ceil($sql_total_row / $post_per_page);if($number_page<=1) return false;
$uls ='<ul class="pagination pagination-sm">';
$a = parse_url($url);
if(isset($a['query']))$url .= '&';else $url .= '?';
$url .= $parameter.'=';
$urls = '';
$distanc = 5;
$f = $current_page-$distanc;
$l = $current_page+$distanc;
$li = function($n,$link,$current_page){ return $current_page==$n ? '<li class="active"><span>'.$n.'</span><li>' : '<li>'.$n.'</li>'; };
for ($i = $current_page; $i > 0; $i--){
if($i>$f or $i < $distanc)
$urls = $li($i,$url.$i.$lasturl,$current_page). $urls;
else{
$i = $distanc;
$urls = '<li><span>...</span><li>'.$urls;
}
}
for ($i = $current_page+1; $i < $number_page; $i++){
if($i<$l or $i > $number_page - $distanc)
$urls .= $li($i,$url.$i.$lasturl,$current_page);
else{
$i = $number_page - $distanc;
$urls.= '<li><span>...</span><li>';
}
}
return $uls.$urls.'</ul>';
}
usage:
$total_row_sql = 1500; //required - get from mysql: SELECT FOUND_ROWS();
$row_display = 50; //required
$parameter_paged = (isset($_GET['paging'])) ? $_GET['paging'] : 1; // required
$custom_url = '/wordpress_url/?'; //custom
$hash = '#target_element_id'; //custom
$name_paramerter_paging = 'paging'; //custom
echo pagination($total_row_sql,$row_display,$parameter_paged,$custom_url,$hash,$name_paramerter_paging);
Result:
view result using pagination
========================================================================
Example if using loop from database:
function select( $table, $field='*', $where='', $order='') {
$sql = "select SQL_CALC_FOUND_ROWS $field from $table";
if($where) $sql.= " where $where";
if($order) $sql.= " order by $order";
$items = $wordpress_mysql->get_results( $sql );// custom: default result object, if u want parse array: ( $sql, ARRAY_A);
$sql_posts_total = $wordpress_mysql->get_var( "SELECT FOUND_ROWS();" );
return (object)['result'=>$items, 'total_rows'=>$sql_posts_total];
}
$result = select('user');
$data_items = $result->result;// foreach show database if u want
$sql_posts_total = $result->total_rows;
$post_per_page = 50;
$parameter_paged = (isset($_GET['paging'])) ? $_GET['paging'] : 1;
echo pagination($sql_posts_total,$post_per_page,$parameter_paged);

PHP Threaded comments pagination

I'm using the threaded comment from http://www.jongales.com/blog/2009/01/27/php-class-for-threaded-comments/ and I have no idea how to implement a pagination system. If anybody could point me in a direction or something because I search for a solution but didn't find anything...
public $parents = array();
public $children = array();
function __construct($comments)
{
foreach ($comments as $comment)
{
if ($comment['parent_id'] === NULL)
{
$this->parents[$comment['id']][] = $comment;
}
else
{
$this->children[$comment['parent_id']][] = $comment;
}
}
}
private function format_comment($comment, $depth)
{
If($depth == 0){
?>
<br /><?php echo $comment['name']; ?><br /><?php echo $comment['datetime']; ?><br /><?php echo $comment['text']; ?></div>
Raspunde
<div id="<?php echo $comment['id']; ?>" style="display: none;">
The content in this div will hide and show (toggle) when the toggle is pressed.
</div>
<?php
}
If($depth > 0){
?>
<div style="margin-left: 20px;">
<br /><?php echo $comment['name']; ?><br /><?php echo $comment['datetime']; ?><br /><?php echo $comment['text']; ?></div>
</div>
<?php
}
}
private function print_parent($comment, $depth = 0)
{
foreach ($comment as $c)
{
$this->format_comment($c, $depth);
if (isset($this->children[$c['id']]))
{
$this->print_parent($this->children[$c['id']], $depth + 1);
}
}
}
public function print_comments()
{
foreach ($this->parents as $c)
{
$this->print_parent($c);
}
}}
$username = "Netra";
$SQL = "SELECT * FROM profile_comments WHERE name = '$username' ORDER BY datetime DESC";
$result = mysql_query($SQL) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
$id = $row['id'];
$parent_id = $row['parent_id'];
$name = $row['name'];
$text = $row['text'];
$datetime = $row['datetime'];
$comments[] = array(
'id' => $id,
'parent_id' => $parent_id,
'name' => $name,
'text' => $text,
'datetime' => $datetime
);
}
$threaded_comments = new Threaded_comments($comments);
$threaded_comments->print_comments();
Pagination simply will change two things in your queries. It will set the LIMIT and OFFSET different based on the current page. There are a few parts involved, mainly knowing the offset. This is easy, it is always the (PAGE_NUMBER * NUMBER_PER_PAGE) - NUMBER_PER_PAGE. You then dynamically change your sql based on the current page!
It looks something like this:
<?php
class Pagination{
public $total_results;
public $total_pages;
public $per_page;
public $offset;
public $page;
public function __construct($per_page=20, $total_results=0, $page=1){
$this->per_page = $per_page;
$this->total_results = $total_results;
$this->page = $page;
$this->set_total_pages();
$this->set_offset();
$this->prepare_displays();
}
public function set_total_pages(){
$this->total_pages = ceil($this->total_results / $this->per_page);
}
public function set_offset(){
$this->offset = ($this->page * $this->per_page) - $this->per_page;
}
public function has_next_page(){
if($this->page < $this->total_pages){
return true;
}else{
return false;
}
}
public function has_previous_page(){
if($this->total_pages > 1 && $this->page > 1){
return true;
}else{
return false;
}
}
public function check_page_exists(){
return (($this->total_pages > 0) && ($this->page > $this->total_pages)) || $this->page < 1 ? false : true;
}
}
?>

Categories