I have inherited a website that was abandoned by it's designer, the guy started with a CMS called Simple Content Management. The core of the system works fine and i am figuring out all the ins and outs of the admin slowly, but surely.

My issue is his page nav special edit for navigating through advertisements that are displayed one at a time. The information is all obtained through MySQL.

Currently the script goes << < 1 > >>

The client wants << < 1 2 3 4 5 > >>

This is probably an easy fix, but I am not that experienced in the coding end of things. The code doesn't deal with rows and I have spent hours trying to figure out where to change something that will make this happen.

I have 3 pages involved, a .tpl , init.php and the display page pro.php. If I have any clue what I am doing this special edit he did in the init.php is where I need to tweek something, I think!

I probably am throwing alot more code at you than i need to, but I wanted to make sure you understood what I am dealing with here.

Can anyone make sense of it and drop me a clue?

error_reporting(E_ALL & ~E_NOTICE);
session_start();

// [ UTF WITHOUT BOM]
include('database.php');
include('func_database.php');
include('func_theme.php');
include('func_form.php');
include('func_files.php');
include('func_seo.php');
include('func_menu.php');
include('func_auth.php');
include('func_mail.php');
include('func_misc.php');
include('func_banners.php');

$sc->webTitle = "SCM";
$sc->admin = 'admvdin_session';
$sc->base = basename($_SERVER[PHP_SELF]);

function MultiStipSlashes(&$arr)
{
        if (is_array($arr))
            foreach ($arr as $list => $key)
            {
                if (is_array($key))
                    MultiStipSlashes($arr[$list]);
                else
                    $arr[$list] = addslashes($key);
            }
}

MultiStipSlashes($_POST);
MultiStipSlashes($_GET);
extract($_POST);
extract($_GET);

function pages($tb, $url, $perpage='20', $where='')
{
    global $sc, $page;
    $cquery = mysql_fetch_array(mysql_query("SELECT COUNT(*) as count FROM ".$tb." ".$where));
    $count = $cquery[count];
    if ($sc->perpage && $page != 'all') $perpage = $sc->perpage;
    else if ($page == 'all') 
    {
        $sc->limit = '0';
        $sc->perpage = $count;
    }
    if (!$page || $page == 1) $sc->limit = 0;
    else if ($page != 'all') $sc->limit = $page * $perpage - $perpage;
    if ($page != 'all' && $count != 0)
    {
        if (!$page) $page = 1;
        $pages = ceil($count / $perpage);

        $npages = $pages - $page;
        if ($page > 1) $pagelst[] = '<a href="'.$url.'&page='.($page-1).'">'.($page-1).'</a>';
        if ($page != $pages) $gonext = ' | <a href="'.$url.'&page='.($page+1).'">Next</a> ';
        if ($page > 1) $goprev = ' <a href="'.$url.'&page='.($page-1).'">Prev</a> | ';

        $next = ($page + 3);
        if ($next > $pages) $next = $pages;

        for ($i=$page; $i<=$next; $i++)
        {
            $pagelst[] = '<a href="'.$url.'&page='.$i.'" '.($i == $page ? 'style="font-weight: bold;"' : '').'>'.$i.'</a>';
        }
        $pagenav = $prev.implode($pagelst, ' | ');
    }

    if ($page != 'all')
        $txt = 'Pages: '.$goprev.$pagenav.$gonext.' [ <a href="'.$url.'&page=all">All</a> ]';
    else
        $txt = 'Showing '.$count.' pages';
    if ($count == 0) unset($txt);

    return $txt;
}

// SPECIAL EDIT

function propages($tb, $url, $perpage='20', $where='', $pr, $id)
{
    global $sc, $page;
    $cquery = mysql_fetch_array(mysql_query("SELECT COUNT(*) as count FROM ".$tb." ".$where));
    $count = $cquery[count];
    if ($sc->perpage && $page != 'all') $perpage = $sc->perpage;
    else if ($page == 'all') 
    {
        $sc->limit = '0';
        $sc->perpage = $count;
    }
    if (!$page) $page = 1;
    if (!$page || $page == 1) $sc->limit = 0;
    else if ($page != 'all') $sc->limit = $page * $perpage - $perpage;
    if ($page != 'all' && $count != 0)
    {
        if (!$page) $page = 1;
        //$pages = (ceil($count / $perpage)-1);
        $pages = ceil($count / $perpage);

        // add javascript limit to page
        $sc->java_pages = 'var total_pages = '.$pages.';';

        $npages = $pages - $page;

        if ($count > $page) $gonext = '<a href="javascript: getBanners(\''.$pr.'\', \''.($page+1).'\', 1, '.($page+1).', '.$id.');"><img src="simages/nextAr.jpg" /></a>&nbsp;&nbsp;&nbsp;';
        //if ($count > ($page+1)) $gonext = '<a href="javascript: getBanners(\''.$pr.'\', \''.($page+1).'\', 20, '.($page+1).', '.$id.');" id="_'.$id.'"><img src="simages/nextAr.jpg" /></a>&nbsp;&nbsp;&nbsp;';
        if ($page !=1 && $page) $goprev = '&nbsp;&nbsp;&nbsp;<a href="javascript: getBanners(\''.$pr.'\', \''.($page-1).'\', 1, '.($page-1).', '.$id.');"><img src="simages/prevAr.jpg" /></a>';
        if ($page > 1) $first = '<a href="javascript: getBanners(\''.$pr.'\', \'0\', 1, 1, '.$id.');"><img src="simages/firstAr.jpg" /></a>&nbsp;&nbsp;&nbsp;';
        if ($page != $pages && $pages != 1) $last = '&nbsp;&nbsp;&nbsp;<a href="javascript: getBanners(\''.$pr.'\', \''.($pages-2).'\', 1, '.$pages.', '.$id.');"><img src="simages/lastAr.jpg" /></a>';

    }

    $txt = $first.$goprev.'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span id="thisPage">'.$page.'</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.$gonext.$last;
    return $txt;
}

function goto($url)
{
    if ($url)
        header("Location: ".$url);
    else
        header("Location: ".$sc->webAdd);
}

function lst($tb, $pos, $where='')
{
    // function get table name and position, build select box with order
    global $sc;
    $lst = mysql_query("SELECT * FROM ".$tb." ".($where ? "WHERE ".$where : '')." ORDER BY lst");
    $txt .= '<select name="db[lst]">'."\n";
    if ($pos) $txt .= '<option value="'.$pos.'">At the same place</option>'."\n";
    $txt .= '<option value="0">First</option>'."\n";
    while ($ww = mysql_fetch_array($lst, MYSQL_ASSOC))
    {
        $txt .= '<option value="'.$ww['lst'].'.5">After '.$ww['title'].'</option>'."\n";
    }
    $txt .= '</select>'."\n";

    return $txt;

I thank everyone and anyone than can help with this issue, I have other issues with this site I will share and deal with after I solve this one.

Thanks,
Tek

Member Avatar for diafol

Quick look:

$txt = $first.$goprev.'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span id="thisPage">'.$page.'</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.$gonext.$last;
return $txt;

Seems to be outputting the current page in the middle of:

<< (first), < (previous), > (next) and >> (last)

You need to change .$page. to have previous pages before it (if they exist) and next pages after it (if they exist).

Sorry, I ain't got the energy to go any further at the moment, hopefully somebody else can give you a quick fix.

You need to think of how many pages (max number) should be displayed before and after the current one. If you've got a 100 pages, you probably don't want to list them all. There was a post earlier this week (in php forum) looking at a snippit to do just that.

<< < 1 2 3 [B]4[/B] ... 34 35 36 > >>

E.g. if you think of displaying a maximum of 10 pages. Say you have 27 pages and your current page is no. 15 - which pages do you want to display (as clickable links)?

1 2 3 ... 14 15 16 ... 24 25 26 27

11 12 13 14 15 16 17 18 19 ... 27

etc.

Decide on your display rules before trying to code, you'll save a lot of hassle. However, if you've only got a small number of pages and don't envisage outgrowing your display space, it's relatively straightforward. Perhaps looking at how something like Google manages pagination may be useful. Sorry couldn't be more help.

Thanks a lot, when I wrote the client wants << < 1 2 3 4 5 > >>
that's it, nothing fancy, nothing major. 5 clickable pages in the display is plenty, I'll look more at what you are explaining to me, hopefully someone can give me a simple, go to this line and change this to this answer. My brain is fried from searching through code at the moment.

Anybody else have a simple answer?

I have few question:
1. As I understand. The code in the first post, one that is now used, is it?

2. Do you have a place of storage for all pages of the project or they are stored somewhere?

3. Finally you say - "I have 3 pages involved, a .tpl , init.php and the display page pro.php" - You possess a remarkable model to implement of the right architecture project. It's Single responsibility principle.

Use that. *.tpl - template file. Which to display markup. init.php - Interface's file; pro.php - invoke to logic pagination.

4. What are the macros use for templates (i.e. *. tpl files): as it "%<macros>%" or variables style($macros)?

Please give more information about the storage your pages into DB.

Maybe it help.

class Mock {
    const PERPAGE = 5;
}

class Init {
    
    public function Navigation($page) {
        $pages = new Paginator($page);
        
        echo "<table>"; 
        for($i = 0; $i < Mock::PERPAGE; $i++) { 
         echo "<tr>
                 <td>" . $pages->posts[$i]['id'] . "</td>
                 <td>" . $pages->posts[$i]['name'] . "</td></tr>
               <tr><td colspan=\"2\">" . $pages->posts[$i]['name'] . "</td></tr>"; 
        } 
        echo "</table>";
        
        if ( $pages->page != 1 ) { 
            $pervpage = '<a href="index.php?page=1"> << </a><a href="index.php?page='. ( $pages->page - 1 ) .'"> < </a> '; 
        }
        if ( $pages->page != $pages->total) { 
        $nextpage = ' <a href="index.php?page=' . ($pages->page + 1) . '"> > </a><a href="index.php?page=' . $pages->total . '"> >> </a>'; 
        }
        if($pages->page - 2 > 0) { $page2left = ' <a href="index.php?page=' . ($pages->page - 2) . '">' . ($pages->page - 2) . '</a> | '; } 
        if($page - 1 > 0) $page1left = '<a href="index.php?page=' . ($pages->page - 1) . '">' . ($pages->page - 1) . '</a> | '; 
        if($pages->page + 2 <= $pages->total) $page2right = ' | <a href="index.php?page=' . ($pages->page + 2) . '" > ' . ($pages->page + 2) . '</a>'; 
        if($pages->page + 1 <= $pages->total) $page1right = ' | <a href="index.php?page=' . ($pages->page + 1) . '" > ' . ($pages->page + 1) . '</a>';
        
        echo $pervpage . $page2left . $page1left . '<b>' . $pages->page . '</b>' . $page1right . $page2right . $nextpage; 
    }
}

class Paginator {
    
    public $total;
    public $posts = array();
    
    public function __construct($page) {
        if( ! is_numeric($page) || empty($page) || $page <= 0 ) {
            $this->page = 1;
        }
        $this->total = intval(($this->NumRows() - 1) / Mock::PERPAGE) + 1;
        if ( $page > $this->total ) {
            $this->page = $this->total;
        }
        $this->page = $page;
    }

    private function NumRows() {
        $row = mysql_query("SELECT id FROM pages");
        $row = mysql_num_rows($row);
        return $row;
    } 
   
    private function setStartPage() {
        return $this->page * Mock::PERPAGE - Mock::PERPAGE;
    }
    
    private function postsByLimit() {
        $this->setStartPage();
        return mysql_query("SELECT * FROM pages LIMIT " . $this->start . ", " . Mock::PERPAGE . ""); 
    }
    
    private function posts() {
       while ( $this->posts[] = mysql_fetch_array($this->postsByLimit()));
    }
}

Hi Samael,

OK, you want more info? Here you go and I will try to insert it properly for the forum admin :-)

Yes, the first post contains the init.php info. The pages are not pages, they are ads in a box at the bottom of the page and they are banners. Listed in a DB and displayed just wonderfully. I want to do absolutely nothing, but change the nav display from << < 1 > >> to << < 1 2 3 4 5 > >>, that's it. I was looking in many places and thought I could change this by switching something simple, I was wrong.

Now I am here and asking for help!

The .tpl is just placement, so not an issue. This is the display page info from pro.php:

// get bottom banners
			$selB = db_get('banners', "proid='".$db[id]."'", 'fetch');
			$pagenav = propages('banners', $sc->base.'?do=list', $sc->perpage, "WHERE parent='".$selB[id]."'", $selB[id], $db[id]);
			$query = mysql_fetch_array(mysql_query("SELECT * FROM banners WHERE parent='".$selB[id]."' ORDER BY lst LIMIT ".$sc->limit.", ".$sc->perpage));
			$sc->banners = stripslashes($query[content]);
			//$sc->banners = "SELECT * FROM banners WHERE parent='".$selB[id]."' ORDER BY lst LIMIT ".$sc->limit.", ".$sc->perpage;
			$sc->pageNav = $pagenav;
			
			$sc->theme = 'inner';
			buildPage();

I just want to know where I need to insert changes to get the results I need, it is driving me insane!

I figured I should throw in the .tpl info just to show you it is not necessary for this task:

<tr>
						<td class="bannersSep"><a name="banners"></a></td>
					</tr>
					<tr>
						<td class="navWarpper">
							<div class="navTitle">
								Professional for {title}
							</div>
							<div id="nav">
								{pageNav}
							</div>
						</td>
					</tr>
					</table>

Thanks,
Tek

Ok! I see. Now I know where should change the code.

Change your 'propages' method. Test this implementation and reporting about bugs if they will be.

function propages($tb, $url, $perpage='20', $where='', $pr, $id)
{
global $sc, $page;
$cquery = mysql_fetch_array(mysql_query("SELECT COUNT(*) as count FROM ".$tb." ".$where));
$count = $cquery[count];
if ($sc->perpage && $page != 'all') $perpage = $sc->perpage;
else if ($page == 'all')
{
$sc->limit = '0';
$sc->perpage = $count;
}
if (!$page) $page = 1;
if (!$page || $page == 1) $sc->limit = 0;
else if ($page != 'all') $sc->limit = $page * $perpage - $perpage;
if ($page != 'all' && $count != 0)
{
if (!$page) $page = 1;
//$pages = (ceil($count / $perpage)-1);
//$pages = ceil($count / $perpage); //old code
//XXX: calculation total count navigation pages
$pages = intval(($count - 1) / $perpage) +1; //new code
//XXX: navigation pages limit
$navlimit = 5;
//XXX: paginator markup
//TODO: make it simply. Need create several methods addbefore() , addafter(), countrow() and etc.
if ( is_numeric($page) ) {
    $summary = $navlimit - $page;
    $paginator = '&nbsp;<span id="thisPage">' . $page . '</span>'; 
    switch ($summary) {
        case $summary > 0:
            if ($navlimit > $page) {
                $after_p = $page + 1;
                $i = 1;
                while ( $after_p <= $navlimit ) {
                    $paginator = $paginator . '&nbsp;<a href="javascript: getBanners(\'' . $pr . '\', \'' . $after_p . '\', 1, ' . $after_p . ', '.$id.');">' . $after_p . '</a>';
                    $after_p++;
                    $i++;
                }
            }
            $before_p = $navlimit - $i;
            $start = 1;
            $str = '';
            while ( $start <= $before_p ) {
                    $str .= '&nbsp;<a href="javascript: getBanners(\'' . $pr . '\', \'' . $start . '\', 1, ' . $start . ', '.$id.');">' . $start . '</a>';
                    $start++;
            }
            $paginator = $str . $paginator;
            break;
        case $summary < 0:
            $countrow = ceil($page / $navlimit);
            $endrow = $navlimit * $countrow;
            if ( $endrow > $page ) {
                $p = $page + 1;
                $after_p = $page + 1; 
                $i = 1;
                while ( $after_p <= $endrow ) {
                    $paginator = $paginator . '&nbsp;<a href="javascript: getBanners(\'' . $pr . '\', \'' . $p . '\', 1, ' . $p . ', '.$id.');">' . $p . '</a>';
                    $p++;
                    $after_p++;
                    $i++;
                }
            }
            if ( $i > 0 ) {
                $before_p = $navlimit - $i;
                $start = $page - $before_p;
                $str = '';
                while ( $start < $page ) {
                    $str .= '&nbsp;<a href="javascript: getBanners(\'' . $pr . '\', \'' . $start . '\', 1, ' . $start . ', '.$id.');">' . $start . '</a>';
                    $start++;
                }
                $paginator = $str . $paginator;
            }
            break;
    }
}
// add javascript limit to page
$sc->java_pages = 'var total_pages = '.$pages.';';

$npages = $pages - $page;

if ($count > $page) $gonext = '<a href="javascript: getBanners(\''.$pr.'\', \''.($page+1).'\', 1, '.($page+1).', '.$id.');"><img src="simages/nextAr.jpg" /></a>&nbsp;&nbsp;&nbsp;';
//if ($count > ($page+1)) $gonext = '<a href="javascript: getBanners(\''.$pr.'\', \''.($page+1).'\', 20, '.($page+1).', '.$id.');" id="_'.$id.'"><img src="simages/nextAr.jpg" /></a>&nbsp;&nbsp;&nbsp;';
if ($page !=1 && $page) $goprev = '&nbsp;&nbsp;&nbsp;<a href="javascript: getBanners(\''.$pr.'\', \''.($page-1).'\', 1, '.($page-1).', '.$id.');"><img src="simages/prevAr.jpg" /></a>';
if ($page > 1) $first = '<a href="javascript: getBanners(\''.$pr.'\', \'0\', 1, 1, '.$id.');"><img src="simages/firstAr.jpg" /></a>&nbsp;&nbsp;&nbsp;';
if ($page != $pages && $pages != 1) $last = '&nbsp;&nbsp;&nbsp;<a href="javascript: getBanners(\''.$pr.'\', \''.($pages-2).'\', 1, '.$pages.', '.$id.');"><img src="simages/lastAr.jpg" /></a>';

}

$txt = $first.$goprev.'&nbsp;&nbsp;&nbsp;&nbsp;' . $paginator . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.$gonext.$last;
return $txt;
}

my jabber : kirweb@gmail.com
and my ICQ : 556885725

Thanks Samael,

It looks great, I am leaving for the evening...so I will check it out when I get back.

Thanks again,
Tek

My time 01:52 PM, now. Hehe))) Where are you from? I'm from Ukraine.

It looks good Samael,

But the navigation doesn't work, it is probably my fault.

I found an ajax.js that connects to the getbanners process:

// [ AJAX SCRIPT FILE ]
function ajaxObject()
{
	var obj = null;
	
	if (window.XMLHttpRequest)
	{
		obj = new XMLHttpRequest;
		return obj;
	} 
	
	if (window.ActiveXObject)
	{
		obj = new ActiveXObject("Microsoft.XMLHTTP");
		return obj;
	}else
	if (window.ActiveXObject)
	{
		obj = new ActiveXObject("Microsoft.XMLHTTP") || new ActiveXObject("Msxml2.XMLHTTP");
		return obj;
	}
}

function getMedia()
{
	var xhr = new ajaxObject();
	var title = gid('q').value;
	if (title.length > 0)
	{
		gid('re').style.display = "block";
	}
	else
	{
		gid('re').style.display = "none";
	}
	
	var url = "media.php";
	var params = "do=ajax_search&q="+title;
	xhr.open("POST", url, true);

	//Send the proper header information along with the request
	xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xhr.setRequestHeader("Content-length", params.length);
	xhr.setRequestHeader("Connection", "close");

	xhr.onreadystatechange = function() {//Call a function when the state changes.
		if(xhr.readyState == 4 && xhr.status == 200) {
			gid('re').innerHTML = xhr.responseText;
		}
	}

	xhr.send(params);
}

function srcalt(src,alt)
{
	// SCRIPT IS FOR WYSIWYG USAGE ONLY
	window.opener.document.getElementById('src').value = src;
	window.opener.document.getElementById('alt').value = alt;
	window.close();
}

var oldSel = '';
var gparent = '';
function getNewPageNav(id, page)
{
	var xhr = new ajaxObject();
	var url = "pro.php";
	var params = "do=shownav&id="+id+"&page="+page;
	xhr.open("POST", url, true);
	//Send the proper header information along with the request
	xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xhr.setRequestHeader("Content-length", params.length);
	xhr.setRequestHeader("Connection", "close");
	
	xhr.onreadystatechange = function() 
	{	//Call a function when the state changes.
		if(xhr.readyState == 4 && xhr.status == 200) {
			gid('nav').innerHTML = xhr.responseText;
		}
	}
	xhr.send(params);
}

// parent, limit lower, per page , current page to get next

function getBanners(parent, llm, ppage, page, id)
{
	if (page >= 1 && page <= total_pages)
	{
		if (parent) gparent = parent;
		parent = gparent;
		getNewPageNav(id, page);
			
		var xhr = new ajaxObject();
		var url = "banners.php";
		var params = "parent="+parent+"&llm="+llm+"&ppage="+ppage;
		xhr.open("POST", url, true);
		//$(document).ready(function(){
			$("#bannersZone").hide();
			$("#bannersZone").slideToggle('slow');
		//});
		//Send the proper header information along with the request
		xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xhr.setRequestHeader("Content-length", params.length);
		xhr.setRequestHeader("Connection", "close");
		
		xhr.onreadystatechange = function() 
		{	//Call a function when the state changes.
			if(xhr.readyState == 4 && xhr.status == 200) {
				gid('bannersZone').innerHTML = xhr.responseText;
			}
		}
		xhr.send(params);
	} else alert('Please wait while loading..');
}

I think this may have been something missing!

I inserted the script and got the 12345 > >> displayed, but it won't go anywhere, just 404 errors.

Is it the ajax script I forgot? Is it creating a problem?

Thanks so much you are awesome Samael!

Jim

Hi Samael,

It works!! I had to pull out some <b></b> that's you put after the javascript, after I did that it works. When I get past the 5th ad it displays << < 1 2 3 4 5 5 > >>, I have not figured that one out yet!

I want to get that fixed and pull it over to the center and make it so the last page does not move to the right when the > >> are not there.

When it gets to << < 6 7 8 9 10 it jumps to the right margin of the table. How do I make that stop happening?

It is close!! You do nice work!!

Thanks,
Jim

Well, I'll try to understand why. I just do not have a full understanding of the application code and it's make barriers to upgrade existing code, but I'll try fix as extrasens. I'll create mock of objects as in your system.

If you can get for me a limited view of code via FTP (or some way) it's will be fine. Another needed to me thing it's website address. With these data I'll correct CMS on the fly.

For create mock of the database I need to know the structure of the table from which the data are taken for display navigation.

OK, I will see what I can do about zipping you a copy of the program and a DB dump.

The website is www.canadahandymen.ca/index.php, click on any of the professionals and at the bottom is where I am trying to get the navigation.

The client plays around with content alot, so do not be surprised to see some strange content.

Thanks

The function "getNewPageNav" returns new page from "pro.php" after request 'do = shownav'. See what happens in the file 'pro.php' after it receives this request. Better send this file (pro.php) on my email box: kirweb@gmail.com.

OK, I will see what I can do about zipping you a copy of the program and a DB dump.

The website is www.canadahandymen.ca/index.php, click on any of the professionals and at the bottom is where I am trying to get the navigation.

The client plays around with content alot, so do not be surprised to see some strange content.

Thanks

Such a decision would be most correct. Especially since I'll not use for commercial purposes your program , don't worry. Quality of code leaves much to be desired)) I was easier to write his own, than edit it))

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.