Need Pagination Script For MVC - php

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.

Related

Links go to the wrong URL

I have a multilingual website, when I change the language to kz, and click on the news link, the url goes to mysite.com/ru/news, how can I make the links in kz go to mysite.com/kz/news?
links are formed in the model_press.php file
<?php
class Model_press extends Model
{ var $content;
function get_pages($offset, $limit){
$offset = intval($offset);
$limit = intval($limit);
if($this->raz_pages['year_raz'] == false){
}
if ($this->raz_pages['year_raz']>0){
$Qstr=" razid ='".$this->raz_pages['year_raz']."'";
}
else {
$stmt1 = Model::$db->prepare("select * from menu where level =22 order by id ");
$stmt1->execute();
$history_raz=array();
$history_names=array();
while($links= $stmt1->fetch(PDO::FETCH_ASSOC)){
$history_raz[$links['link']]="'".$links['id']."'";
$history_names[$links['link']]=$this->utils->translate_tex(array('name_ru'=>$links['name_ru'], 'name_kz'=>$links['name_kz'], 'name_en'=>$links['name_en']));
}
$Qstr=" razid in(".implode(",", $history_raz)." )";}
$this->years=$history_names;
$stmt2 = Model::$db->prepare("select * from articles where ".$Qstr." order by id desc LIMIT ".$limit." OFFSET ".$offset);
$stmt2->execute();
while($con= $stmt2->fetch(PDO::FETCH_ASSOC)){
$cont=$this->utils->translate_tex($con);
$cont['id'] = $con['id'];
$cont['razname']=$history_names[$con['raz']]['name'];
$this->content[$con['razid']][]=$cont;
}
}
function get_pages1(){
$stmt1 = Model::$db->prepare("select * from menu where level='22' order by name_ru");
$stmt1->execute();
while($con= $stmt1->fetch(PDO::FETCH_ASSOC)){
$this->npages[]=$con['name_ru'];
if($con['name_ru']==$this->raz_pages['year']){$this->raz_pages['year_raz']=$con['id'];}
}
}
function getcurentnews($id){
$stmt1 = Model::$db->prepare("select * from articles where id =".$id);
$stmt1->execute();
while($con= $stmt1->fetch(PDO::FETCH_ASSOC)){
$cont=$this->utils->prerare_tex($con);
$this->content[]=$cont;
}
//print_r($content);
}
function get_shownew(){
if ($this->model->raz_pages);
}
function get_othernews($id){
$stmt = Model::$db->prepare("select * from menu where level =22 order by id desc");
$stmt->execute();
$history_raz=array();
$history_names=array();
while($links= $stmt->fetch(PDO::FETCH_ASSOC)){
$history_raz[$links['link']]="'".$links['id']."'";
$history_names[$links['link']]=$this->utils->translate_tex(array('name_ru'=>$links['name_ru'], 'name_kz'=>$links['name_kz'], 'name_en'=>$links['name_en']));
}
$stmt1 = Model::$db->prepare("select * from articles where razid in(".implode(",", $history_raz).") and id <> ".$id." order by id desc limit 2");
$stmt1->execute();
while($con= $stmt1->fetch(PDO::FETCH_ASSOC)){
$cont=$this->utils->translate_tex($con);
$cont['razname']=$history_names[$con['raz']]['name'];
$this->contentother[$con['raz']][]=$cont;
}
return $this->contentother;
// print_r($this->content);
}
function get_pressCount(){
$stmt = Model::$db->prepare("select * from articles where razid in(23, 32)");
$stmt->execute();
return $stmt->rowCount();
}
function set_pages(){
$this->raz_pages=array();
if (intval(Route::$routes[1])>0){
$this->raz_pages['year']=Route::$routes[1];
}
if (intval(Route::$routes[2])>0 and Route::$routes[1]=='page'){ // press/page/2
$this->raz_pages['page']=Route::$routes[2];
}
if (intval(Route::$routes[1])>0 and intval(Route::$routes[3])>0 and Route::$routes[2]=='page'){ // press/2019/page/2
$this->raz_pages['page']=Route::$routes[3];
}
if (intval(Route::$routes[1])>0 and isset(Route::$routes[2])){// press/2910/111-newname
$this->raz_pages['year']=Route::$routes[1];
$newar=explode("-",Route::$routes[2]);
if (isset($newar[0]) and intval($newar[0])>0){
$this->raz_pages['id']=$newar[0];
}
}
}
// function eror_page(){
// if ($this->raz_pages['year'] > 0 and !isset($this->raz_pages['year']) ){
// Route::ErrorPage_404();
// }
// }
}
controller_press.php file
<?php
class Controller_press extends Controller
{
function __construct()
{
$this->model = new Model_press();
$this->view = new View();
}
function action_index()
{
$this->model->html_headers();
$this->model->set_pages();
$this->model->get_pages1();
if (isset($this->model->raz_pages['id']) and $this->model->raz_pages['id']>0){$this->shownew($this->model->raz_pages);}
else {$this->news_list();}
$image = "<img>";
if($image > 0) {
}
$this->model->eror_page();
$this->right_news();
}
function shownew($arr){
//print_r($arr);
$this->model->getcurentnews($arr['id']);
$this->model->html_headers();
$this->view->ar['routes']=Route::$routes[1];
$this->model->removecss('my.css');
$this->model->addcss('front.css');
$this->model->addcss('animate.css');
$this->model->addsript('viewportchecker.js');
$this->model->addsript('front.js');
$this->model->loadscripts();
$data = $this->model->content;
//print_r($data);
if($data[0]['img'] != ''){
$image ='<figure class="card__image">
<img src="'.$data[0]['img'].'" alt="упс картинка пропал НАчальника" >
</figure>';
}else {
$image = null;
}
$this->model->get_othernews($arr['id']);
$dataother = $this->model->contentother;
$out='';
foreach ($dataother as $key => $value) {
foreach ($value as $key1 => $value1) {
$card_border = '';
$card_image = '';
$bottom_text = '<div class="card__desc destroy_text">'.$value1['tex'].'</div>';
$im = '';
if(trim($value1['img']) != '' and file_exists($_SERVER['DOCUMENT_ROOT'].''.$value1['img']))
{
$card_border= null;
$img='<a href="/press/'.$value1['razname'].'/'.$value1['id'].'-'.$this->model->utils->str2url($value1['name']).'" >
<figure class="card__image">
<img src="'.$value1['img'].'" alt="" >
</figure></a>';
} else {
$card_border = 'card--border';
$card_image = null;
$img = null;
}
if(trim($value1['head']) == '' and trim($value1['img']) != ''){
$card_image = 'card--image';
$card_border = null;
$bottom_text = '';
}
$head_text='';
if ($value1['pubdat'] != ''){
$head_text.= '<div class="card__period"><span class="period">'.$value1['pubdat'].'</span></div>';
} else {
$head_text.= '';
}
$out.= '<div class=" blockblock '.$card_border.''.$card_image.'">
'.$img.'
<div class="card__body">
'.$head_text.'
<h4 class="card__title">
'.$value1['name'].'
</h4>
'.$bottom_text.' </div>
</div>';
}
}
$out.='';
$this->view->ar['pubdat']=$data[0]['pubdat'];
$this->view->ar['img']=$data[0]['img'];
$this->view->ar['tex']=$data[0]['tex'];
$this->view->ar['name']=$data[0]['name'];
$this->view->ar['head']=$data[0]['head'];
$this->view->ar['image'] = $image;
$this->view->ar['context']= $out;
$this->view->ar['getPage'] = null;
$this->view->ar['year'] = null;
$fils=array( 'front/top.tpl', 'front/press_underblock.tpl', 'front/bottom.tpl');
$this->view->SendFiles($fils);
$this->view->Parse();
$this->view->Show();
}
function news_list(){
$this->model->html_headers();
$this->view->ar['routes']=Route::$routes[1];
$this->model->removecss('my.css');
$this->model->addcss('front.css');
$this->model->addcss('animate.css');
$this->model->addsript('viewportchecker.js');
$this->model->addsript('front.js');
$this->model->loadscripts();
$page = $page === false ? 1 : $page;
$this->pressPage(Route::$page);
$data = $this->model->get_pages($this->offset, $this->limit);
$data=$this->model->content;
arsort($data);
$year='<ul class="pagination__list">';
foreach ($this->model->years as $key => $value) {$year.='<li><a href="/press/'.$value['name'].'/" class="link pagination__link" >'.$value['name'].'</a></li>';}
$year.=' </ul>';
$out='';
foreach ($data as $key => $value) {
foreach ($value as $key1 => $value1) {
$card_border = '';
$card_image = '';
$text='<div class="card__desc destroy_text">'.$value1['tex'].'</div>';
$im = '';
if(trim($value1['img']) != '' and file_exists($_SERVER['DOCUMENT_ROOT'].''.$value1['img']))
{
$card_border= null;
$info = getimagesize($_SERVER['DOCUMENT_ROOT'].''.$value1['img']);
$im=$this->model->image->GetThumb(''.$value1['img'], 1, 500, 500);
$img='<a href="/press/'.$value1['razname'].'/'.$value1['id'].'-'.$this->model->utils->str2url($value1['name']).'" >
<figure class="card__image">
<img src="'.$im.'" alt="" >
</figure></a>';
} else {
$card_border = 'card--border';
$card_image = null;
$img = null;
}
if(trim($value1['head']) == '' and trim($value1['img']) != ''){
$card_image = 'card--image';
$card_border = null;
$text='';
}
$head_text='';
if ($value1['pubdat'] != ''){
$head_text='<div class="card__period"><span class="period">'.$value1['pubdat'].'</span></div>';
} else {
$head_text.= '';
}
$out.= '<div class="tiles__card card card--promo '.$card_border.' '.$card_image.'">
'.$img.'
<div class="card__body">
'.$head_text.'
<h4 class="card__title">
'.$value1['name'].'
</h4>
<em> '.$value1['head'].' </em>'.$text.'
</div>
</div>';
}
}
$out.='';
// Добавил дату чекай
$this->view->ar['pubdat']=$data['pubdat'];
$this->view->ar['tex1']=$data['tex'];
$this->view->ar['name1']=$data['name'];
$this->view->ar['head']=$data['head'];
$this->view->ar['img']=$data['img'];
$this->view->ar['context']=$out;
$this->view->ar['year'] = $year;
$this->view->ar['news_block'] = null;
$yearses = $this->model->years;
if($this->model->raz_pages['year'] > 0 ){
$press = 'press/page/';
} else {
$press = 'press/page/';
}
$this->view->ar['getPage'] = $this->model->utils->paginationPress($press, $this->totalPages, $page);
$fils=array( 'front/top.tpl', 'front/press.tpl', 'front/bottom.tpl');
$this->view->SendFiles($fils);
$this->view->Parse();
$this->view->Show();
}
function pressPage($page) {
if($page == false)
$page = 1;
$this->limit = 10;
$this->counts = $this->model->get_pressCount();
$this->totalPages = ceil($this->counts / $this->limit);
$this->offset = ($page - 1) * $this->limit;
}
}
some links work correctly, for example, when I click on the History link, the transition is done at URL website.com/kz/history

How to hide categories which is not having any products in magento?

I am showing products categories after clicking on any Brand but i want to hide those categories which do no have any products. I am trying from last 6 hours to find the solution but no solution i have found
here is my code below :
<?php
//Image Adjustment
$config = Mage::getModel('manufacturers/image_config');
$image = Mage::getModel('media/image');
$image->setConfig($config);
//Get Manfacturer Info
$mId = $this->getRequest()->getParam('id');
/****************Category Collection**********************/
$manufacturersTable = Mage::getSingleton('core/resource')->getTableName('manufacturers');
$manufacturersProductsTable = Mage::getSingleton('core/resource')->getTableName('manufacturers_products');
$sqry = "SELECT mp.product_id,mp.manufacturers_id FROM ".$manufacturersTable." m
INNER JOIN ".$manufacturersProductsTable." AS mp ON m.manufacturers_id = mp.manufacturers_id
WHERE m.manufacturers_id = ".$mId;
$connection = Mage::getSingleton('core/resource')->getConnection('core_read');
$select = $connection->query($sqry);
$prds = $select->fetchAll();
$categoryIds=array();
$i=0;
foreach ($prds as $_manufacturer) {
$productIds= $_manufacturer["product_id"];
$_product=Mage::getModel('catalog/product')->load($productIds);
$categoryIds = array_merge($_product->getCategoryIds(), $categoryIds);
$i++;
}
$product=Mage::getModel('catalog/product')->load($prds[0]['product_id']);
$manufacturer = $_product["manufacturer"];
if(empty($manufacturer))
{
$manufacturer = $product->getManufacturer();
}
?>
<?php if ($mId != 0 ) { ?>
<?php
$model = Mage::getModel('manufacturers/manufacturers')->load($mId);
$x = Mage::helper('manufacturers')->getLogoWidth();
$y = Mage::helper('manufacturers')->getLogoHeight();
$color = Mage::helper('manufacturers')->getLogoBackgroundColor();
if($model["m_logo"] != "") {
$imgPath = Mage::helper('manufacturers')->getResizedUrl($model["m_logo"],$x,$y,$color);
} else {
$imageFile = "manufacturers/files/n/i/no_image_available.jpg";
$imgPath = Mage::helper('manufacturers')->getResizedUrl($imageFile,$x,$y,$color);
}
?>
$rootCatId = 257; // haikal 257
$catids=array();
$cat='';
function getTreeCategories($parentId, $isChild){
$allCats = Mage::getModel('catalog/category')->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('is_active','1')
->addAttributeToFilter('include_in_menu','1')
->addAttributeToFilter('parent_id',array('eq' => $parentId))
->addAttributeToSort('position');
$class = ($isChild) ? "sub-cat-list" : "cat-list";
foreach ($allCats as $category)
{
$html .= $category->getID().',';
$subcats = $category->getChildren();
if($subcats != ''){
$html .= getTreeCategories($category->getId(), true);
}
}
return $html;
}
$catlistHtml = getTreeCategories($rootCatId, true);
//echo $catlistHtml;
($catlistHtml=explode(',', $catlistHtml));
if(count($_GET)) {
?>
<script>
function abc()
{
window.location = window.location.href.split("?")[0];
}
</script>
<div id="whole-cat" class="whole-cat" style="display:none;">
<?php
}
else{
?>
<div id="whole-cat" class="whole-cat" style="display:block">
<?php
}
global $showleftNav;
if(!$showleftNav)
{
$o = null;
$o .= '<div class="content">';
$_columnCount = 5;
$i = 0;
$j = 0;
foreach ($catlistHtml as $_category) {
// if the category is not match the product categories
if(!in_array($_category, $categoryIds)) continue;
$i++;
$_category = Mage::getModel('catalog/category')->load($_category);
//$_category = $_category->load($catId);
$imgurl=$_category->getImageUrl();
$products_count = Mage::getModel('catalog/category')->load($_category->getId())->getProductCount();
if($products_count==0) continue;
if(empty($imgurl))
{
$imgurl=$this->getSkinUrl('images/small_image.jpg');
}
if ($j++%$_columnCount==0):
$o .= '<ul class="pro-cat">';
endif;
$o .= '<li id="m'.$manufacturer.'" class="categoryName row'.$i.'"><h4>'.$_category->getName().'</h4><img src="'.$imgurl.'" ></li class="totalNumberOfProducts">';
if ($j%$_columnCount==0):
$o .= '</ul>';
endif;
}
echo $o;
?>
<?php
$showleftNav==true;
}
?>
</div>
</div>
</div>
In output i have seen that no category is hide
I have tried almost everything i have tried to get Category id by name so that i can search the category and get its id and apply filter.
My page link
Here is the details explanation about this feature:
http://prattski.com/2011/10/06/magento-module-hide-empty-categories/

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;
}
}
?>

mysql_fetch_object is very slow takes about 30 seconds to load with only 20 ROWS [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Simplest way to profile a PHP script
We are building this online application using MVC approach (but a bit tweeked).
The structure of the application goes like this.
class Page{
private $title;
private $css;
private $type;
private $formData;
private $obj;
public function __construct($type){
//this instance variable is designed to set form data which will appear on the pages
$this->formData = array();
$this->setup($type);
}
public function setTitle($var){
$this->title = 'Page : ';
$this->title .= $var;
}
public function getFormData() {
return $this->formData;
}
private function setFormData($tmpObjs) {
$finData = array();
foreach($tmpObjs as $value){
if($value == $this->obj && isset($_GET['new']))
$newValue = 'true';
else
$newValue = 'false';
$tmpData = array();
$tmpData = $value->getData($newValue);
$finData = array_merge($finData, $tmpData);
}
return $finData;
}
public function getTitle(){
return $this->title;
}
public function displayCSS($_SESSION){
$GlobalConfig = $_SESSION['Config'];
$CSS = array();
$CSS = $GlobalConfig->getCSS();
$SIZE = count($CSS);
foreach($CSS as $key => $value){
echo "<link href=\"".$CSS[$key]."\" type=\"text/css\" rel=\"stylesheet\" />\n";
}
}
public function displayJS($_SESSION){
$GlobalConfig = $_SESSION['Config'];
$JS = array();
$JS = $GlobalConfig->getJS();
$SIZE = count($JS);
foreach($JS as $key => $value){
echo "<script src=\"".$JS[$key]."\" type=\"text/javascript\"></script>\n";
}
}
function setPageType($type)
{
$this->type = $type;
}
// This is used when you are filtering whatever type for search function
function getPageType(){
$type = $this->type;
echo $type;
}
function setup($type){
$this->type = $type;
switch($this->type){
case "AccountExpiry":
break;
case "Home":
$CalendarExpiryItemList = new CalendarExpiryItemList();
$CalendarExpiryItemList->createList();
$_SESSION['Active_Form'] = 'homepage-record';
$this->obj = $CalendarExpiryItemList;
$objs = array($CalendarExpiryItemList);
$this->formData = $this->setFormData($objs);
$this->setTitle('Home');
break;
}
}
function generateJS(){
if(file_exists('../classes/Javascript.class.php'))
include_once '../classes/Javascript.class.php';
$JSType = str_replace(" " , "", ucwords(str_replace("-", " ", substr(end(explode("/", $_GET['page'])), 0, -4))));
$JSType = $_GET['page'];
if(substr($JSType, -1) == 's')
$JSType = substr ($JSType, 0, -1);
echo $JSType;
$new_obj_name = $JSType . "JS";
$jsObj = new $new_obj_name($this->type);
}
function getObject(){
return $this->obj;
}
//There is more code, file has been omitted for forum
}
The following is the CalendarExpiryItemList class
class CalendarExpiryItemList
{
private $List = array();
public function __construct()
{
//Nothing To Do Yet
}
public function createList($Type = "Followups")
{
switch($Type)
{
case "ALL":
$this->List = array();
$this->getAllItemsInArray();
return $this->List;
break;
case "Invoice":
$this->List = array();
$this->getInvoiceCalendarItems();
return $this->List;
break;
case "Followups":
$this->List = array();
$this->getFollowUpExpiryItems();
return $this->List;
break;
}
}
public function _compare($m, $n)
{
if (strtotime($m->getExpiryDate()) == strtotime($n->getExpiryDate()))
{
return 0;
}
$value = (strtotime($m->getExpiryDate()) < strtotime($n->getExpiryDate())) ? -1 : 1;
echo "This is the comparison value" . $value. "<br/>";
return $value;
}
public function display()
{
foreach($this->List as $CalendarItem)
{
echo "<tr>";
if($CalendarItem->getType() != "ContractorInsurance")
echo "<td>".DateFormat::toAus($CalendarItem->getExpiryDate())."</td>";
else
echo "<td>".$CalendarItem->getExpiryDate()."</td>";
echo "<td>".$CalendarItem->getType()."</td>";
echo "<td>".$CalendarItem->getDescription()."</td>";
echo "<td>".$CalendarItem->doAction()."</td>";
echo "</tr>";
}
}
public function getData()
{
$data = array();
$data['Rows'] = "";
$TempArray1 = array();
foreach($this->List as $CalendarItem)
{
$Temp = "";
$Temp .= "<tr>";
if($CalendarItem->getType() != "ContractorInsurance")
$Temp .= "<td>".DateFormat::toAus($CalendarItem->getExpiryDate())."</td>";
else
$Temp .= "<td>".$CalendarItem->getExpiryDate()."</td>";
$Temp .= "<td>".$CalendarItem->getType()."</td>";
$Temp .= "<td>".$CalendarItem->getDescription()."</td>";
$Temp .= "<td>".$CalendarItem->doAction()."</td>";
$Temp .= "</tr>";
$TempArray1[] = $Temp;
}
if(count($TempArray1) == 0)
{
$Row = "<tr><td colspan='4'>No Items overdue</td></tr>";
$TempArray1[] = $Row;
}
$data['Rows'] = $TempArray1;
return $data;
}
//---------------Private Functions----------------
private function SortArrayDate()
{
$TempArray = array();
$TempArray = $this->List;
$this->List = array();
foreach($TempArray as $CalendarItem)
{
$this->List[$CalendarItem->getExpiryDate()] = $CalendarItem;
}
ksort($this->List);
}
private function getAllItemsInArray()
{
$this->getInvoiceCalendarItems();
$this->getFollowUpExpiryItems();
$this->getProjectExpiryItems();
$this->getVehicleExpiryItems();
$this->getUserInsuranceExpiryItems();
$this->getContractorExpiryItems();
//$this->SortArrayDate();
}
private function getContractorExpiryItems()
{
$SQL = "SELECT * FROM `contractor_Details` WHERE `owner_id` =".$_SESSION['user_id'];
$RESULT = mysql_query($SQL);
while($row = mysql_fetch_object($RESULT))
{
$InsLic = new ContractorInsLis();
$InsLic->getContractorInsLisById($row->contractor_id);
if($InsLic->CheckExpiry($InsLic->getwcic_expiry_date()) == 'Expired')
{
$ContractorExpiryItem = new ContractorInsuranceExpiryItem($row->contractor_id,$InsLic->getwcic_expiry_date(),"Contractor ".$row->first_name." ".$row->last_name."'s Workers Comp License expired on ".$InsLic->getwcic_expiry_date());
$this->List[] = $ContractorExpiryItem;
}
if($InsLic->CheckExpiry($InsLic->getpli_expiry_date()) == 'Expired')
{
$ContractorExpiryItem = new ContractorInsuranceExpiryItem($row->contractor_id,$InsLic->getpli_expiry_date(),"Contractor ".$row->first_name." ".$row->last_name."'s Public Liability Insurance expired on ".$InsLic->getpli_expiry_date());
$this->List[] = $ContractorExpiryItem;
}
if($InsLic->CheckExpiry($InsLic->getcontractor_expiry_date()) == 'Expired')
{
$ContractorExpiryItem = new ContractorInsuranceExpiryItem($row->contractor_id,$InsLic->getcontractor_expiry_date(),"Contractor ".$row->first_name." ".$row->last_name."'s Contractor License expired on ".$InsLic->getcontractor_expiry_date());
$this->List[] = $ContractorExpiryItem;
}
if($InsLic->CheckExpiry($InsLic->getwcic_expiry_date()) == 'Expired')
{
$ContractorExpiryItem = new ContractorInsuranceExpiryItem($row->contractor_id,$InsLic->getcompany_expiry_date(),"Contractor ".$row->first_name." ".$row->last_name."'s Company License expired on ".$InsLic->getcompany_expiry_date());
$this->List[] = $ContractorExpiryItem;
}
}
}
private function getUserInsuranceExpiryItems()
{
$SQL = "SELECT * FROM `user_my_insurances_licences` WHERE `user_id`=".$_SESSION['user_id'];
$RESULT = mysql_query($SQL);
while($row = mysql_fetch_object($RESULT))
{
$UserInsuranceLicenses = new UserMyLicenseInsurance();
if($UserInsuranceLicenses->CheckExpiry($row->DL_expiry_date) == 'Expired')
{
$ExpiredItem = new UserInsuranceExpiryItem($_SESSION['user_id'],$row->DL_expiry_date,"DL #".$row->DL_number." has expired on ".$row->DL_expiry_date);
$this->List[] = $ExpiredItem;
}
if($UserInsuranceLicenses->CheckExpiry($row->CL_expiry_date) == 'Expired')
{
$ExpiredItem = new UserInsuranceExpiryItem($_SESSION['user_id'],$row->CL_expiry_date,"CL #".$row->CL_number." has expired on ".$row->CL_expiry_date);
$this->List[] = $ExpiredItem;
}
if($UserInsuranceLicenses->CheckExpiry($row->BL_expiry_date) == 'Expired')
{
$ExpiredItem = new UserInsuranceExpiryItem($_SESSION['user_id'],$row->BL_expiry_date,"BL #".$row->BL_number." has expired on ".$row->DL_expiry_date);
$this->List[] = $ExpiredItem;
}
if($UserInsuranceLicenses->CheckExpiry($row->wcic_expiry_date) == 'Expired')
{
$ExpiredItem = new UserInsuranceExpiryItem($_SESSION['user_id'],$row->wcic_expiry_date,"Workers Compe #".$row->wcic_policy_number." has expired on ".$row->wcic_expiry_date);
$this->List[] = $ExpiredItem;
}
if($UserInsuranceLicenses->CheckExpiry($row->pli_expiry_date) == 'Expired')
{
$ExpiredItem = new UserInsuranceExpiryItem($_SESSION['user_id'],$row->pli_expiry_date,"Public Liability #".$row->pli_policy_number." has expired on ".$row->pli_expiry_date);
$this->List[] = $ExpiredItem;
}
if($UserInsuranceLicenses->CheckExpiry($row->cwi_expiry_date) == 'Expired')
{
$ExpiredItem = new UserInsuranceExpiryItem($_SESSION['user_id'],$row->cwi_expiry_date,"Contract Worker Insurance #".$row->cwi_policy_number." has expired on ".$row->cwi_expiry_date);
$this->List[] = $ExpiredItem;
}
if($UserInsuranceLicenses->CheckExpiry($row->hoi_expiry_date) == 'Expired')
{
$ExpiredItem = new UserInsuranceExpiryItem($_SESSION['user_id'],$row->hoi_expiry_date,"Home Owners Insurance #".$row->hoi_policy_number." has expired on ".$row->hoi_expiry_date);
$this->List[] = $ExpiredItem;
}
if($UserInsuranceLicenses->CheckExpiry($row->pii_expiry_date) == 'Expired')
{
$ExpiredItem = new UserInsuranceExpiryItem($_SESSION['user_id'],$row->pii_expiry_date,"Professional Indemnity Owners Insurance #".$row->pii_policy_number." has expired on ".$row->pii_expiry_date);
$this->List[] = $ExpiredItem;
}
if($UserInsuranceLicenses->CheckExpiry($row->tic_expiry_date) == 'Expired')
{
$ExpiredItem = new UserInsuranceExpiryItem($_SESSION['user_id'],$row->tic_expiry_date,"Tools Insurance #".$row->tic_policy_number." has expired on ".$row->tic_expiry_date);
$this->List[] = $ExpiredItem;
}
}
}
private function getVehicleExpiryItems()
{
$SQL = "SELECT * FROM `user_my_motor_vehicles` WHERE `user_id` =".$_SESSION['user_id'];
$RESULT = mysql_query($SQL);
while($row = mysql_fetch_object($RESULT))
{
$UserMotorVehicles = new UserMotorVehicles();
if($UserMotorVehicles->CheckExpiry($row->vehicle_registration_expiry_date) == 'Expired')
{
$VehicleRegistration = new VehicleExpiryItem($row->id,$row->vehicle_registration_expiry_date,"Vehicle ".$row->vehicle_reg_no." Registration Expired on ".$row->vehicle_registration_expiry_date);
$this->List[] = $VehicleRegistration;
}
if($UserMotorVehicles->CheckExpiry($row->insurance_expiry_date) == 'Expired')
{
$VehicleInsurance = new VehicleExpiryItem($row->id,$row->insurance_expiry_date,"Vehicle ".$row->vehicle_reg_no." Insurace Expired on ".$row->insurance_expiry_date);
$this->List[] = $VehicleInsurance;
}
}
}
private function getProjectExpiryItems()
{
$SQL = "SELECT * FROM my_project WHERE user_id =".$_SESSION['user_id']." AND ((end_date < '".date('Y-m-d')."') OR (end_date = '".date('Y-m-d')."') OR end_date='0000-00-00') AND (actual_end_date = '' OR actual_end_date = ' ' OR actual_end_date = '0000-00-00')";
$RESULT = mysql_query($SQL);
while($row = mysql_fetch_object($RESULT))
{
$Project = new ProjectExpiryItem($row->project_id,$row->end_date,"Project ".$row->project_name." was due on ".$row->end_date,$row->start_date);
$this->List[] = $Project;
}
}
private function getInvoiceCalendarItems()
{
$SQL = "SELECT * FROM project_invoices WHERE (dueDate < '".date('Y-m-d')."') AND (date_paid ='0000-00-00' OR date_paid='') AND (user_id = ".$_SESSION['user_id'].") LIMIT 0, 10";
$RESULT = mysql_query($SQL);
while($row = mysql_fetch_object($RESULT))
{
$Invoice = new InvoiceExpiryItem($row->id,$row->invoice_date,"Invoice #".$row->id." is overdue.");
//testObj(array($Invoice));
$this->List[] = $Invoice;
}
}
private function getFollowUpExpiryItems()
{
$SQL = "SELECT * from followUps WHERE owner_id=".$_SESSION['user_id']." AND ((Date_Due < '".date('Y-m-d')."') OR (Date_Due = '".date('Y-m-d')."') OR (Date_Due = '0000-00-00')) AND Completed != '1'";
$RESULT = mysql_query($SQL);
while($row = mysql_fetch_object($RESULT))
{
$Form_Id = new FormId();
$Description = "Follow Up on ".$Form_Id->getFormNam($row->Form_id)." was due on ".$row->Date_Due;
$FollowUp = new FollowUpExpiryItem($row->Id,$row->Date_Due,$Description);
$this->List[] = $FollowUp;
}
}
This is the pagination Class
<?php
class Pagination {
protected $Items = array();
protected $Type = "default";
protected $Title = "List of ";
protected $Base_Url = "";
protected $Table;
//-------------------------Table Settings----------------//
protected $No_Of_Columns = NULL;
protected $No_Of_Items_Per_Page = 10; //By Default 10 items will be displayed on a page.protected
protected $Present_Page = 0;
protected $Columns = array();
protected $Rows = array();
//------------------------Table Class Attributes---------//
protected $Table_Class = "";
protected $Table_Id = "";
protected $GETVarName = "PP";
/**
*
*/
public function __construct()
{
$this->Table = false;
}
public function paginate()
{
//Check if the base url is set
if(strlen($this->Base_Url) == 0){
echo "Error: Could not paginate, No base url Found!";
}
//Set the Current page value to Present Page
if(isset($_GET))
{
if(isset($_GET[$this->GETVarName])){
$this->Present_Page = intval($_GET[$this->GETVarName]);
} else {
$this->Present_Page = 1;
}
}
//Draw the table and the values
$this->generatePaginationTable();
}
public function setData($data)
{
if(is_array($data)){
$this->Rows = $data;
return true;
} else {
return false;
}
}
public function putData($object,$functionName = "generateRow")
{
$TempData = array();
if(method_exists($object,"getObjs"))
{
$ObjectArray = $object->getObjs();
}
if(method_exists($object,$functionName))
{
foreach($ObjectArray as $Obj)
{
$TempData[] = $object->$functionName($Obj);
}
}
$this->setData($TempData);
unset($TempData);
}
public function setIsTable($val)
{
$this->IsTable = $val;
}
public function addColumnNames($Col){
if(is_array($Col)){
$this->No_Of_Columns = $Col;
} else {
return false;
}
}
/**
* #param $config (array)
* #return bool
*
* this function initializes the Pagination object with the
* initial values
*/
public function initialize($config)
{
if(is_array($config))
{
foreach($config as $key => $value)
{
if(isset($this->$key))
{
$this->$key = $value;
}
}
} else if(is_object($config)) {
return false;
} else if(is_string($config)){
return false;
}
}
//------------------------------Private Function For the Class-------------------------//
private function generatePaginationTable()
{
if($this->Table){
$this->StartTable();
$this->DisplayHeader();
}
$this->DisplayData();
$this->DisplayLinks();
if($this->Table)
echo "</table>";
}
private function DisplayLinks()
{
if($this->Table){
echo "<tr>";
echo '<td colspan="'. count($this->Rows) .'">';
$this->GenerateLinkCounting();
echo '</td>';
echo "</tr>";
} else {
if(count($this->Rows) > 0)
{
$ROW = $this->Rows[0];
$ColSpan = substr_count($ROW,"<td");
echo "<tr>";
echo '<td colspan="'. $ColSpan .'" align="right">';
$this->GenerateLinkCounting();
echo '</td>';
echo "</tr>";
}
}
}
private function GenerateLinkCounting()
{
$this->Base_Url .= $this->getOtherGetVar();
$StartCount = 1;
$EndCount = count($this->Rows) / $this->No_Of_Items_Per_Page;
for($i=0; $i < $EndCount; $i++)
{
if($i == 0)
{
echo ' <a href="'. $this->Base_Url.'&'.$this->GETVarName .'='.intval($i+1). '" >First</a> ';
} else if($i == intval($EndCount)){
echo ' <a href="'. $this->Base_Url.'&'.$this->GETVarName .'='.intval($i+1).'" >Last</a> ';
} else {
echo ' <a href="'. $this->Base_Url.'&'.$this->GETVarName .'='.intval($i+1). '" >'.intval($i+1).'</a> ';
}
}
}
private function getOtherGetVar()
{
$Link = "";
if(isset($_GET))
{
foreach($_GET as $key => $val)
{
if($key != $this->GETVarName)
{
$Link .= "&".$key."=".$val;
}
}
}
$h = preg_split("/&/",$this->Base_Url);
$this->Base_Url = $h[0];
return $Link;
}
private function DisplayData()
{
$Index = 0;
$StartIndex = intval(intval($this->Present_Page-1) * $this->No_Of_Items_Per_Page);
$EndIndex = intval($StartIndex + $this->No_Of_Items_Per_Page);
foreach($this->Rows as $Row)
{
$Index++;
if($Index >= $StartIndex && $Index <= $EndIndex)
{
echo "<tr>";
if(is_array($Row))
{
foreach($Row as $key => $value){
echo "<td>".$value."</td>";
}
} else {
echo $Row;
}
echo "</tr>";
}
}
}
private function DisplayHeader()
{
if(is_array($this->Columns))
{
echo "<thead>";
echo "<tr>";
foreach($this->Columns as $Col => $value)
{
echo "<td>".$value."</td>";
}
echo "</tr>";
echo "</thead>";
}
}
private function StartTable()
{
echo "<table ";
if(strlen($this->Table_Class) > 0)
echo 'class="'.$this->Table_Class.'" ';
if(strlen($this->Table_Id) > 0)
echo 'id="'.$this->Table_Id.'" ';
echo ">";
}
}
Final Implementation of the File
<?php
$Page = new Page('Home');
$data = $Page->getFormData();
$Pagination = new Pagination();
$config = array();
$config['Table'] = false;
$config['No_Of_Items_Per_Page'] = 25;
$config['Base_Url'] = base_url() . 'BootLoader.php?page=Homepage';
$config['GETVarName'] = "ODL";
$Pagination->initialize($config);
$Pagination->setData($data['Rows']);
/**
* Want to have multiple lists
*/
$CalendarExpiryList = $Page->getObject();
$CalendarExpiryList->createList("Invoice");
$InvoiceList = new Pagination();
$config = array();
$config['Table'] = false;
$config['No_Of_Items_Per_Page'] = 25;
$config['Base_Url'] = base_url() . 'BootLoader.php?page=Homepage';
$config['GETVarName'] = "OIDL";
$InvoiceList->initialize($config);
$data2 = $CalendarExpiryList->getData();
$InvoiceList->setData($data2['Rows']);
//This is the display
include_once("Forms/homepage/home-page.html.php");
?>
The PHP Script runs fine. It takes about 0.03 to load.
But when the script reaches the CalendarExpiryItemList class. It takes about 30 seconds and my server times out.
Each table would have around 12 to 15 fields on an average and about 10 to 100 records to go through.
I am on hosting with a hosting company they have load balancers. So if my scripts takes more than 30 seconds the load balancer resets my connection and return an error saying "Server sent no data"
As the others say you should try profile your code.
...without being able to debug the code, maybe one or more of the methods in CalendarExpiryItemList class is failing at some point either; on the query, or associated query, or returning a endless loop. You should test and debug each method individually on a your test server to see what results your getting. For a quick and dirty test, just log the output of each method to a file. Also check $_SESSION['user_id'] has a value and use ". (int) $_SESSION['user_id'] as well before sending it the db in case its empty because its not escaped.

Categories