Консультация № 186776
04.11.2012, 11:27
99.97 руб.
0 0 0
Здравствуйте, уважаемые эксперты! Прошу вас ответить на следующий вопрос: Мне надо сделать пагинацию такого вида и где то в коде ошибка
Оригинальный который сейчас


Надо такого плана на первой странице:


на последующих страницах:


имеется код где прописана пагинация
Код:
<?php
// Core class by Boris.
// Handles various requests from user page like selecting data from db, sorting by etc...

class core {
public $db; // database handler
public $umem = 0; // use memcache? 0 / 1
public $mem = false; // memcache object

// sql select range for pagination
public $pstart = 0; // pagination start
public $plimit = 0; // pagination limit
public $page = 1; // page requested?

private $p; // pagination class

public $months_ru = array(
1 => 'января',
2 => 'февраля',
3 => 'марта',
4 => 'апреля',
5 => 'мая',
6 => 'июня',
7 => 'июля',
8 => 'августа',
9 => 'сентября',
10 => 'октября',
11 => 'ноября',
12 => 'декабря'
);

public $pageRequest = 'index.php';

public function __construct( $use_memcache = 1 ) {
$this->db = new db( array('dbhost' =>'localhost','dbuser' =>'brestiki', 'dbpass' =>'pass','dbname' => 'brestiki', 'dbport' => 3306) );

$this->umem = $use_memcache;

if ( $this->umem ) {
$this->mem = new Memcache();
$this->mem->connect('localhost', 11211);
}

$this->plimit = QUOTES_PER_PAGE;

$arr = explode('/', $_SERVER['SCRIPT_NAME']);
$this->pageRequest = end($arr);
}

// Declare function to convert to JSON

public function _json_encode($a = false) {
if (is_null($a))
return 'null';
if ($a === false)
return 'false';
if ($a === true)
return 'true';
if (is_scalar($a)) {
if (is_float($a)) {
$a = str_replace(",", ".", strval($a));
}

static $jsonReplaces = array(array("\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '"'));
return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
}
$isList = true;
for ($i = 0, reset($a); $i < count($a); $i++, next($a)) {
if (key($a) !== $i) {
$isList = false;
break;
}
}
$result = array();
if ($isList) {
foreach ($a as $v)
$result[] = $this->_json_encode($v);
return '[' . join(',', $result) . ']';
} else {
foreach ($a as $k => $v)
$result[] = $this->_json_encode($k) . ': ' . $this->_json_encode($v);
return '{' . join(',', $result) . '}';
}
}

public function getPaging() {
$pagination = '';

$brestiks_count = array();
$brestiks_count['amount'] = 0;

if ( !$this->mem || !$this->mem->get('pages') ) {

$pagination_query = "SELECT COUNT(id) AS `amount` FROM `brestiki` WHERE `date_show` <= NOW() LIMIT 1";

$get_pages_amount = $this->db->query( $pagination_query );
$brestiks_count = $this->db->fetch_assoc($get_pages_amount);
$brestiks_count['amount'] = intval($brestiks_count['amount']);

if ( $this->mem ) {
$this->mem->set('pages', $brestiks_count['amount'],MEMCACHE_COMPRESSED,300);
}

} else {
$brestiks_count['amount'] = intval($this->mem->get('pages'));
}

if ( $brestiks_count['amount'] > 0) {
$plus_page = 0;
if ( $brestiks_count['amount'] % QUOTES_PER_PAGE > 0 ) {
$plus_page++;
}
$pages_amount = floor ( $brestiks_count['amount'] / QUOTES_PER_PAGE + $plus_page );
} else {
$pages_amount = 1;
}

//$this->page = (!empty($_GET['page']) ? intval($_GET['page']) : 1); // $pages_amount

$this->page = (!empty($_GET['page']) ? intval($_GET['page']) : $pages_amount);

$this->pstart = ($this->page < 1 || $this->page >= $pages_amount ? ($brestiks_count['amount']-QUOTES_PER_PAGE) : $brestiks_count['amount']-($pages_amount-$this->page+($this->page == 1 ? 0 : 1))*QUOTES_PER_PAGE);
$this->plimit = QUOTES_PER_PAGE;

if ($this->page == 1) {
$this->pstart = 0;
$this->plimit = $brestiks_count['amount'] % QUOTES_PER_PAGE;
}


// Draw pagination cell

$pagination = '<div class="pagination">';

for ($i = $pages_amount; $i > 0; $i-- ) {
// Lets draw the pagination
$pagination .= "<a ".($i == $this->page ? 'class="active"' : '')." href="".SITEURL.$this->pageRequest."?page=$i">$i</a> ";
}

// Close the pagination DIV

$pagination .= '</div>';

return $pagination;
}

public function getBrestiksBySearch($query, $pageId)
{
$sphinx = new Sphinx_Client();
$sphinx->SetServer('localhost', 3312);
$perpage = 10;
$sphinx->SetLimits(($pageId-1)*$perpage, $perpage, 500);

$result = $sphinx->Query($query, 'brestiki');

$html = array();
$html['content'] = '';
$html['paginator'] = '';

$total = intval($result['total']);

if ($result && isset($result['matches']) && is_array($result['matches']))
{
$dbQuery = "SELECT `id`, `date_added`, `content`, `rating` FROM `brestiki` WHERE `id` IN (".implode(',', array_keys($result['matches'])).") ORDER BY `rating`";
$dbResult = $this->db->query($dbQuery);

$brestiks = array();
while ($brestik = $this->db->fetch_assoc($dbResult)) {
$brestiks[] = $brestik;
}

foreach($brestiks as $k => $brestik )
{
$html['content'] .= "<div class="shell" id="".$brestik["id"]."">
<div class="id"><a href="brestik.php?brestik=".$brestik["id"]."">#".$brestik["id"]."</a></div>
<div class="rating">".$brestik["rating"]."</div>
<div class="vote" id="".$brestik["id"]."">Нравится!</div>";

$html['content'] .= "<div class="date">".$this->getPostDate($brestik["date_added"])."</div>
<div class="share"><a href="javascript:;" onclick="shareItem('http://vkontakte.ru/share.php?url=".urlencode("http://brestiki.com/brestik.php?brestik=".$brestik["id"]."&utm_source=sharing&utm_campaign=vkontakte")."&title=".urlencode($brestik["content"])."'); return false;"><img src="static/16x16/vkontakte.png"></a> 
<a href="javascript:;" onclick="shareItem('http://connect.mail.ru/share?url=".urlencode("http://brestiki.com/brestik.php?brestik=".$brestik["id"]."&utm_source=sharing&utm_campaign=mailru")."&imageurl=".urlencode(SITEURL."/static/brestiki_normal.png")."&title=".urlencode("Брестик №".$brestik["id"])."&description=".urlencode($brestik["content"])."'); return false;"><img src="/static/16x16/mailru.png"></a> 
<a href="javascript:;" onclick="shareItem('http://www.facebook.com/sharer.php?u=".urlencode("http://brestiki.com/brestik.php?brestik=".$brestik["id"]."&utm_source=sharing&utm_campaign=facebook")."&t=".urlencode($brestik["content"])."'); return false;"><img src="static/16x16/facebook.png"></a> 
<a onclick='ODKL.Share(this);return false;' href='http://brestiki.com/brestik.php?brestik=".$brestik["id"]."&utm_source=sharing&utm_campaign=odnoklassniki&title=".urlencode($brestik["content"])."'><img src="static/16x16/odnoklassniki.png"></a> 
<a href="javascript:;" onclick="shareItem('http://www.livejournal.com/update.bml?event=".urlencode($brestik["content"].'

<a href="http://brestiki.com/?utm_source=sharing&utm_campaign=livejournal">Читать еще</a>')."&subject=Брестик №".$brestik['id']."'); return false;"><img src="static/16x16/livejournal.png"></a> 
<a href="javascript:;" onclick="shareItem('http://twitter.com/share?text=".urlencode($brestik["content"].' #brestiki ')."&url=".urlencode("http://brestiki.com/brestik.php?brestik=".$brestik["id"]."&utm_source=sharing&utm_campaign=twitter")."'); return false;"><img src="static/16x16/twitter.png"></a> 
<a class="myo-share" target="_blank" href="javascript:;" onclick="shareItem('http://my.opera.com/community/post/?url=".urlencode("http://brestiki.com/brestik.php?brestik=".$brestik["id"])."&title=".urlencode($brestik["content"])."');"><img src="http://static.myopera.com/community/graphics/operashare16.png" /></a></script>
</div>
<div class="brestik">".$brestik["content"]."</div>
</div>";
}

$html['paginator'] = '<div class="pagination">';

for ($i = 1; $i <= ceil($total/$perpage); $i++) {
$html['paginator'] .= "<a ".($i == $pageId ? 'class="active"' : '')." href="".SITEURL.$this->pageRequest."?q=".urlencode($query).($i>1 ? '&page='.$i : '')."">$i</a> ";
}

$html['paginator'] .= '</div>';

} else {
$html['content'] = 'Не найдено брестиков по данному запросу.';
}

return $html;
}

// Getting approved brestiks

public function getBrestiks($page='main') {
$quotes_on_page = '';
$quotesKey = md5($this->page.$this->pstart.$this->pageRequest);

if ( !$this->mem || !$this->mem->get('quotes') || $quotesKey != @$this->mem->get('quotesKey') ) {

// order by ? according to page type
$order_by = 'date_show';
switch( $page ) {
case 'main':
$order_by = '`date_show` ASC';
break;

case 'random':
$order_by = 'rand()';
break;

case 'top':
$order_by = '`rating` DESC';
$this->plimit = 50;
break;

case 'rating':
$order_by = '`rating` ASC';
break;
}

// Outputing quotes
$query = "SELECT `id`, `date_added`, `content`, `rating` FROM `brestiki` WHERE `date_show` <= NOW() ORDER BY ".$order_by." LIMIT " . $this->pstart .', '.$this->plimit;

$get_brests_main = $this->db->query($query);

$quotes_on_page = array();
while ($brestik = $this->db->fetch_assoc($get_brests_main)) {
$quotes_on_page[] = $brestik;
}

if ( $page != 'top' ) {
$quotes_on_page = array_reverse($quotes_on_page);
}

if ( $this->mem ) {
$this->mem->set('quotes', $quotes_on_page,MEMCACHE_COMPRESSED,300);
$this->mem->set('quotesKey', md5($this->page.$this->pstart.$this->pageRequest),MEMCACHE_COMPRESSED,300);
}
} else {
$quotes_on_page = $this->mem->get('quotes');
}

$brestiki = '<span class="cleaner"></span>';

$i = 0;
$c = count($quotes_on_page);


$ads = "



";

foreach( $quotes_on_page as $k => $brestik ) {

// Removed center ads, useless...
if ( $i != NULL && $i >= ($c / 2) ) {

$brestiki .= $ads;

$i = NULL;
}


// Temporary removed google button
// <g:plusone size="small" count="false" href="http://brestiki.com/brestik.php?brestik=".$brestik["id"]."&utm_source=sharing&utm_campaign=gplus"></g:plusone>
$brestiki .= "<div class="shell" id="".$brestik["id"]."">
<div class="id"><a href="brestik.php?brestik=".$brestik["id"]."">#".$brestik["id"]."</a></div>
<div class="rating">".$brestik["rating"]."</div>";

if (basename($_SERVER['PHP_SELF']) != 'rating.php') {

$brestiki .= "<div class="vote" id="".$brestik["id"]."">Нравится!</div>";

}

// April fool fix

//$brestik['content'] = utf8_strrev($brestik['content']);

$brestiki .= "<div class="date">".$this->getPostDate($brestik["date_added"])."</div>
<div class="share"><a href="javascript:;" onclick="shareItem('http://vkontakte.ru/share.php?url=".urlencode("http://brestiki.com/brestik.php?brestik=".$brestik["id"]."&utm_source=sharing&utm_campaign=vkontakte")."&title=".urlencode($brestik["content"])."'); return false;"><img src="static/16x16/vkontakte.png"></a> 
<a href="javascript:;" onclick="shareItem('http://connect.mail.ru/share?url=".urlencode("http://brestiki.com/brestik.php?brestik=".$brestik["id"]."&utm_source=sharing&utm_campaign=mailru")."&imageurl=".urlencode(SITEURL."/static/brestiki_normal.png")."&title=".urlencode("Брестик №".$brestik["id"])."&description=".urlencode($brestik["content"])."'); return false;"><img src="/static/16x16/mailru.png"></a> 
<a href="javascript:;" onclick="shareItem('http://www.facebook.com/sharer.php?u=".urlencode("http://brestiki.com/brestik.php?brestik=".$brestik["id"]."&utm_source=sharing&utm_campaign=facebook")."&t=".urlencode($brestik["content"])."'); return false;"><img src="static/16x16/facebook.png"></a> 
<a onclick='ODKL.Share(this);return false;' href='http://brestiki.com/brestik.php?brestik=".$brestik["id"]."&utm_source=sharing&utm_campaign=odnoklassniki&title=".urlencode($brestik["content"])."'><img src="static/16x16/odnoklassniki.png"></a> 
<a href="javascript:;" onclick="shareItem('http://www.livejournal.com/update.bml?event=".urlencode($brestik["content"].'

<a href="http://brestiki.com/?utm_source=sharing&utm_campaign=livejournal">Читать еще</a>')."&subject=Брестик №".$brestik['id']."'); return false;"><img src="static/16x16/livejournal.png"></a> 
<a href="javascript:;" onclick="shareItem('http://twitter.com/share?text=".urlencode($brestik["content"].' #brestiki ')."&url=".urlencode("http://brestiki.com/brestik.php?brestik=".$brestik["id"]."&utm_source=sharing&utm_campaign=twitter")."'); return false;"><img src="static/16x16/twitter.png"></a> 
<a class="myo-share" target="_blank" href="javascript:;" onclick="shareItem('http://my.opera.com/community/post/?url=".urlencode("http://brestiki.com/brestik.php?brestik=".$brestik["id"])."&title=".urlencode($brestik["content"])."');"><img src="http://static.myopera.com/community/graphics/operashare16.png" /></a></script>
</div>
<div class="brestik">".$brestik["content"]."</div>
</div>";

$i++;
}

return $brestiki;
}


// Getting Bermuda brestiks

public function getBrestiksBer($page='main') {
$quotes_on_page = '';
$quotesKey = md5($this->page.$this->pstart.$this->pageRequest);

if ( !$this->mem || !$this->mem->get('quotesBer') || $quotesKey != @$this->mem->get('quotesKeyBer') ) {

// order by ? according to page type
$order_by = 'id';
switch( $page ) {

// Output random berduda brestiks on main page

case 'random':
$order_by = 'rand()';
break;

case 'rating':
$order_by = '`rating` DESC';
break;
}

// Outputing quotes
$query = "SELECT `id`, `date_added`, `content`, `rating` FROM `bermudy` WHERE `date_show` <= NOW() ORDER BY ".$order_by." LIMIT " . $this->pstart .', '.$this->plimit;

$get_brests_main = $this->db->query($query);

$quotes_on_page = array();
while ($brestik = $this->db->fetch_assoc($get_brests_main)) {
$quotes_on_page[] = $brestik;
}

if ( $this->mem ) {
$this->mem->set('quotesBer', $quotes_on_page,MEMCACHE_COMPRESSED,30);
$this->mem->set('quotesKeyBer', md5($this->page.$this->pstart.$this->pageRequest),MEMCACHE_COMPRESSED,30);
}
} else {
$quotes_on_page = $this->mem->get('quotesBer');
}

$brestiki = '<span class="cleaner"></span>';

$i = 0;
$c = count($quotes_on_page);


$ads = "
<center>
<script type='text/javascript'>
var rnd = Math.floor(Math.random()*99999999999);
document.write("<iframe src='http://server.adeasy.ru/servead/request/864");
document.write("?cb=");
document.write(rnd+"'");
document.write(" width='728' height='90' frameborder='0' scrolling='no'></iframe>");
</script></div></center>


";

foreach( $quotes_on_page as $k => $brestik ) {

// Removed center ads, useless...
if ( $i != NULL && $i >= ($c / 2) ) {

$brestiki .= $ads;

$i = NULL;
}


// Temporary removed google button
// <g:plusone size="small" count="false" href="http://brestiki.com/brestik.php?brestik=".$brestik["id"]."&utm_source=sharing&utm_campaign=gplus"></g:plusone>

// Removed
// <div class="id"><a href="brestik.php?brestik=".$brestik["id"]."">#".$brestik["id"]."</a></div>
// <div class="rating">".$brestik["rating"]."</div>

$brestiki .= "<div class="shell" id="".$brestik["id"]."">

<div class="rating">".$brestik["rating"]."</div>";



if (basename($_SERVER['PHP_SELF']) == 'ball.php') {


$brestiki .= "<div class="vote" id="".$brestik["id"]."">Нравится!</div>";

}

$brestiki .= "<div class="date">".$this->getPostDate($brestik["date_added"])."</div>
<div class="share"><a href="javascript:;" onclick="shareItem('http://vkontakte.ru/share.php?url=".urlencode("http://brestiki.com/&utm_source=sharing&utm_campaign=vkontakte")."&title=".urlencode($brestik["content"])."'); return false;"><img src="static/16x16/vkontakte.png"></a> 
<a href="javascript:;" onclick="shareItem('http://connect.mail.ru/share?url=".urlencode("http://brestiki.com/&utm_source=sharing&utm_campaign=mailru")."&imageurl=".urlencode(SITEURL."/static/brestiki_normal.png")."&title=".urlencode("Брестик №".$brestik["id"])."&description=".urlencode($brestik["content"])."'); return false;"><img src="/static/16x16/mailru.png"></a> 
<a href="javascript:;" onclick="shareItem('http://www.facebook.com/sharer.php?u=".urlencode("http://brestiki.com/&utm_source=sharing&utm_campaign=facebook")."&t=".urlencode($brestik["content"])."'); return false;"><img src="static/16x16/facebook.png"></a> 
<a onclick='ODKL.Share(this);return false;' href='http://brestiki.com/&utm_source=sharing&utm_campaign=odnoklassniki&title=".urlencode($brestik["content"])."'><img src="static/16x16/odnoklassniki.png"></a> 
<a href="javascript:;" onclick="shareItem('http://www.livejournal.com/update.bml?event=".urlencode($brestik["content"].'

<a href="http://brestiki.com/?utm_source=sharing&utm_campaign=livejournal">Читать еще</a>')."&subject=Брестик №".$brestik['id']."'); return false;"><img src="static/16x16/livejournal.png"></a> 
<a href="javascript:;" onclick="shareItem('http://twitter.com/share?text=".urlencode($brestik["content"].' #brestiki ')."&url=".urlencode("http://brestiki.com/&utm_source=sharing&utm_campaign=twitter")."'); return false;"><img src="static/16x16/twitter.png"></a> 
<a class="myo-share" target="_blank" href="javascript:;" onclick="shareItem('http://my.opera.com/community/post/?url=".urlencode("http://brestiki.com/?utm_source=sharing&utm_campaign=opera")."&title=".urlencode($brestik["content"])."');"><img src="http://static.myopera.com/community/graphics/operashare16.png" /></a></script>
</div>
<div class="brestik">".$brestik["content"]."</div>
</div>";

$i++;


}

return $brestiki;
}

public function getBrestik($sid) {
$quotesKey = md5($sid);

if ( !$this->mem || !$this->mem->get('brestik') || $quotesKey != @$this->mem->get('quotesKey') ) {

// Outputing quotes
$query = "SELECT `id`, `date_added`, `content`, `rating` FROM `brestiki` WHERE id=".$sid;

$get_brest_main = $this->db->query($query);

if ( !$get_brest_main || !$this->db->numrows($get_brest_main) ) {
$brestik_out['title'] = '404 - Брестик не найден';
$brestik_out['content'] = '<div class="shell"><div class="id">Фиг вам</div><div class="brestik">Брестик '. $sid .' не найден!</div></div>';
return $brestik_out;
}

$brestik = $this->db->fetch_assoc($get_brest_main);

if ( $this->mem ) {
$this->mem->set('brestik', $brestik,MEMCACHE_COMPRESSED,300);
$this->mem->set('quotesKey', md5($sid),MEMCACHE_COMPRESSED,300);
}
} else {
$brestik = $this->mem->get('brestik');
}

$brestik_out = array();

// Removed mail.ru
//
//
// <g:plusone size="small" count="false" href="http://brestiki.com/brestik.php?brestik=".$brestik["id"]."&utm_source=sharing&utm_campaign=gplus"></g:plusone>


$brestik_out['content'] = "<span class="cleaner"></span><div class="shell" id="".$brestik["id"]."">
<div class="id"><a href="brestik.php?brestik=".$brestik["id"]."">#".$brestik["id"]."</a></div>
<div class="rating">".$brestik["rating"]."</div>
<div class="vote" id="".$brestik["id"]."">Нравится!</div>
<div class="date">".$this->getPostDate($brestik["date_added"])."</div>
<div class="share"><a href="javascript:;" onclick="shareItem('http://vkontakte.ru/share.php?url=".urlencode("http://brestiki.com/brestik.php?brestik=".$brestik["id"]."&utm_source=sharing&utm_campaign=vkontakte")."&title=".urlencode($brestik["content"])."'); return false;"><img src="static/16x16/vkontakte.png"></a> 
<a href="javascript:;" onclick="shareItem('http://connect.mail.ru/share?url=".urlencode("http://brestiki.com/brestik.php?brestik=".$brestik["id"]."&utm_source=sharing&utm_campaign=mailru")."&title=".urlencode("Брестик №".$brestik["id"])."&description=".urlencode($brestik["content"])."'); return false;"><img src="/static/16x16/mailru.png"></a> 
<a href="javascript:;" onclick="shareItem('http://www.facebook.com/sharer.php?u=".urlencode("http://brestiki.com/brestik.php?brestik=".$brestik["id"]."&utm_source=sharing&utm_campaign=facebook")."&t=".urlencode($brestik["content"])."'); return false;"><img src="static/16x16/facebook.png"></a> 
<a onclick='ODKL.Share(this);return false;' href='http://brestiki.com/brestik.php?brestik=".$brestik["id"]."&utm_source=sharing&utm_campaign=odnoklassniki&title=".urlencode($brestik["content"])."'><img src="static/16x16/odnoklassniki.png"></a> 
<a href="javascript:;" onclick="shareItem('http://www.livejournal.com/update.bml?event=".urlencode($brestik["content"].'

<a href="http://brestiki.com/?utm_source=sharing&utm_campaign=livejournal">Читать еще</a>')."&subject=Брестик №".$brestik['id']."'); return false;"><img src="static/16x16/livejournal.png"></a> 
<a href="javascript:;" onclick="shareItem('http://twitter.com/share?text=".urlencode($brestik["content"].' #brestiki ')."&url=".urlencode("http://brestiki.com/brestik.php?brestik=".$brestik["id"]."&utm_source=sharing&utm_campaign=twitter")."'); return false;"><img src="static/16x16/twitter.png"></a> 
<a class="myo-share" target="_blank" href="javascript:;" onclick="shareItem('http://my.opera.com/community/post/?url=".urlencode("http://brestiki.com/brestik.php?brestik=".$brestik["id"])."&title=".urlencode($brestik["content"])."');"><img src="http://static.myopera.com/community/graphics/operashare16.png" /></a></script>

</div>
<div class="brestik">".$brestik["content"]."</div>";

$brestik_out['content'] .= "</div>";

$query = "SELECT `id`, `date_added`, `content`, `rating` FROM `brestiki` WHERE `id` < ".$sid." AND `date_show` <= NOW() ORDER BY `id` DESC LIMIT 1";
$preventBrestik = $this->db->query($query);
if ($preventBrestik || $this->db->numrows($preventBrestik) ) {
$preventBrestik = $this->db->fetch_assoc($preventBrestik);

$brestik_out['content'] .= "<div class="next-brestik"><a href="brestik.php?brestik=".$preventBrestik["id"]."">Следующий брестик</a></div>";
}

$brestik_out['title'] = $brestik["content"];

return $brestik_out;
}

public function getPostDate($time,$type=1) {
$time = strtotime($time);

$m = date('n',$time);
$d = date('d', $time);
$y = date('Y', $time);

$today = strtotime('Today');

$reldays = ($time - $today)/86400;

if ( $reldays >= 0 && $reldays < 1 ) {
return 'Сегодня, ' . date('H:i', $time);
} else if ( $reldays >= -1 && $reldays < 0 ) {
return 'Вчера, ' . date('H:i', $time);
}

if ( !empty($this->months_ru[$m]) ) {
$m = $this->months_ru[$m];
} else {
$m = date('M', $time);
}

return $d . ' ' . $m .', ' . $y . ' ' . date('H:i', $time);
}
}

class pagination {

protected $output = '';
protected $full_url = '';

public $get_page = 1; // Current page that equals to $_GET['page']
public $per_page = 5; // Rows per page
public $display = 0; // How much pages to display at a time

public $total_pages = 0; // Total pages in current mode
public $errorh = ''; // Error Message, if exists

public $plus_page = 0;

public function __construct() {
}

// total_rows - INT how many pages from SQL result, viewport - how much pages to display in a row, per_page - as it sounds
public function buildPaging( $total_rows, $viewport = 0, $per_page = 5, $pageNum = 1 ) {
/* Check if we can work with received arguments to constructor */
$this->get_page = intval($pageNum);
$this->per_page = intval($per_page);

$total_rows = intval($total_rows);
if ( $total_rows > 0 ) {
if ( $total_rows % $this->per_page > 0 ) {
$this->plus_page++;
}
$this->total_pages = floor ( $total_rows / $this->per_page + $this->plus_page );
}
else
{
$this->get_page = 0;
}

$this->display = intval($viewport);

/*$tmp_url = SITEURL;

if (substr($tmp_url, -1) == '/') {
$tmp_url = substr($tmp_url,0,(strlen($tmp_url)-1));
}

$request_url = (!empty($_SERVER['REQUEST_URI']) ? urldecode($_SERVER['REQUEST_URI']) : "");
$qry_str = (!empty($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '');
$request_url = preg_replace('/[\&\?].*[remove_me]/','',$request_url);

if (substr($qry_str, 0) == '&') {
$qry_str = substr($qry_str,1,strlen($qry_str));
}*/

$this->full_url = ltrim(rtrim(SITEURL,'/'),'/');

$this->generateOutput();
return true;
}

private function generateOutput() {

//$this->total_pages = 0;
$tmp_sidenum = ceil ( $this->display / 2 ); // how much pages from every side

$this->output = '';
if ( $this->get_page == 0 || $this->total_pages == 0 )
{
return false;
}

if ( $this->total_pages <= $this->display )
{
$lb = ($this->get_page - $tmp_sidenum >= 1) ? ceil( $this->get_page - $tmp_sidenum + $this->plus_page ) : 1;
$lb = ($lb < $this->display) ? $this->display : $lb;
$up = ($lb + $this->display <= $this->total_pages) ? $lb + $this->display - 1 : $this->total_pages;
}
else
{
$lb = 1;
$up= $this->total_pages;
}

$this->output = '';
//$this->output .= '<div id="pages_select"><div class="select_upper">'; // Open HTML

// First and prev page
if ( $this->get_page != 1 )
{
$this->output .= '<a href="' . $this->full_url . '?page=' . ($this->get_page-1) . '"><</a>';
// moved out of the IF
}

//$this->output .= '  ';
//$this->output .= '<span class="backarrow' . ( ($this->get_page == 1) ? '_d' : '' ) . '">​</span>'/*<a href="' . $this->full_url . '/' . (($this->get_page == 1 ? 1 : $this->get_page - 1)) . '.html" class="numbers">Назад</a>  '*/;

for( $i = $lb; $i <= $up; $i++ )
{
$tmp_ifbold = ( $i == $this->get_page ) ? '_bold' : '';
$selected = ( $i == $this->get_page ) ? '_selected' : '';
if ( !empty( $tmp_ifbold ) ) {
$this->output .= '<a class="active" href="javascript:;">' . $i . '</a>';
} else {
$this->output .= '<a href="' . $this->full_url . '?page=' . $i . '"' . $tmp_ifbold . '">' . $i . '</a>';
}
}

// Last and next
if ( $this->get_page != $this->total_pages )
{
//$this->output .= ' <a href="' . $this->full_url . '/' . ($this->get_page + 1) . '.html" class="numbers">Вперед</a> <span class="goarrow' . ( ($this->total_pages == $this->get_page) ? '_d' : '' ) . '">​</span>';
//$this->output .= '  ';
$this->output .= '<a href="' . $this->full_url . '?page=' . ($this->get_page+1) . '">></a>';
}

//$this->output .= '</div></div>'; // Close HTML
}

public function displayPages() {
return $this->output;
}
}

class db {
public $db;
private $host, $user, $pass, $port;
public $dbname;

private function connect() {
$this->db = @mysql_connect( $this->host, $this->user, $this->pass );

if ( !$this->db ) {
return ('[ERROR]Connection to database failed.');
}

if ( !@mysql_select_db($this->dbname) ) {
return ('[ERROR]Failed to select database.');
}

$this->query("SET NAMES 'utf8'");

return $this->db;
}

public function __construct( $dbc ) {
$this->host = $dbc['dbhost'];
$this->dbname = $dbc['dbname'];
$this->user = $dbc['dbuser'];
$this->pass = $dbc['dbpass'];
$this->port = $dbc['dbport'];

return $this->connect();
}

public function __destruct() {
//$this->close();
}

public function close() {
mysql_close($this->db);
}

public function query($query) {
$record = mysql_query($query, $this->db);

if ( $record ) {
return $record;
}
}

public function query_row($query) {
$result = $this->query($query);
if ($result)
{
$row = $this->fetch_assoc($result,MYSQL_ASSOC);
}
return $row;
}

public function query_array($query) {
$result_array = array();
$result = $this->query($query);
if ( $result )
{
while( $row = $this->fetch_assoc( $result, MYSQL_ASSOC ) )
{
$result_array[] = $row;
}
}
return $result_array;

}

public function insert($table, $data) {
$fields = array_keys($data);
$values = array_values($data);

$sql = 'INSERT INTO ' . $table . ' (`'.(implode('`,`',$fields)).'`) VALUES (\''.(implode('\',\'',$values)).'\')';
$this->query($sql);
$newId = $this->lastid();
if ( $newId ) {
return $newId;
} else {
return false;
}
}

public function insertQuery($table, $data) {
$fields = array_keys($data);
$values = array_values($data);

$sql = 'INSERT INTO ' . $table . ' (`'.(implode('`,`',$fields)).'`) VALUES (\''.(implode('\',\'',$values)).'\')'.";\n";
return $sql;
}

public function insertData($table, $fields, $data_arrs) {

$sql = 'INSERT INTO ' . $table . ' (`'.(implode('`,`',$fields)).'`) VALUES ';
$f = true;
foreach( $data_arrs as $k => $data ) {
$values = array_values($data);

$sql .= ($f ? '' : ',') . '(\''.(implode('\',\'',$values)).'\')';
$f = false;
$this->query($sql);
}

return true;
}

public function insertDataQuery($table, $fields, $data_arrs) {

$sql = 'INSERT INTO ' . $table . ' (`'.(implode('`,`',$fields)).'`) VALUES ';
$f = true;
foreach( $data_arrs as $k => $data ) {
$values = array_values($data);

$sql .= ($f ? '' : ',') . '(\''.(implode('\',\'',$values)).'\')';
$f = false;
}

return $sql . ";\n";
}

public function affected() {
return mysql_affected_rows($this->db);
}

public function lastid() {
return mysql_insert_id($this->db);
}

public function numrows( $recordSet ) {
return (int) mysql_num_rows( $recordSet );
}

public function fetch_assoc( $rec ) {
if ( $rec ) {
$this->query = mysql_fetch_array( $rec, MYSQL_ASSOC );
return $this->query;
} else {
return false;
}
}

public function fetch_num( $recordSet ) {
$this->query = mysql_fetch_array( $recordSet, MYSQL_NUM );
return $this->query;
}

public function escape( $string ) {
return mysql_real_escape_string( $string );
}
}
?>


в индексе подгружается методом
Код:
$pagination = $core->getPaging();
echo $pagination;

Обсуждение

Форма ответа