Jump to content

HELP-My pagination is not working


gnawz

Recommended Posts

Hi experts,

 

Iam designing a system with a couple of files.

 

There is a functions file (functions.php) which contains all functions

 

Files for each module are stored in a folder

Each module has an index page which iterates gthe functions to be performed.

 

 

My functions file (functions.php) which contains the pagination function at the bottom

<?
/* This file contains all functions to be used in the stock system*/

ini_set('display_errors', 'On');

//Error reporting
error_reporting(E_ALL);

// start the session
session_start();

// database connection config
$dbHost = 'localhost';
$dbUser = 'root';
$dbPass = '';
$dbName = 'cstockdb';

$errorMessage;
//DB functions
$dbConn = mysql_connect ($dbHost, $dbUser, $dbPass) or die ('MySQL connect failed. ' . mysql_error());
mysql_select_db($dbName) or die('Cannot select database. ' . mysql_error());

function dbQuery($sql)
{
$result = mysql_query($sql) or die(mysql_error());

return $result;
}

function dbAffectedRows()
{
global $dbConn;

return mysql_affected_rows($dbConn);
}

function dbFetchArray($result) 
{
return mysql_fetch_array($result);
}

function dbFetchAssoc($result)
{
return mysql_fetch_assoc($result);
}

function dbFetchRow($result) 
{
return mysql_fetch_row($result);
}

function dbFreeResult($result)
{
return mysql_free_result($result);
}

function dbNumRows($result)
{
return mysql_num_rows($result);
}

function dbSelect($dbName)
{
return mysql_select_db($dbName);
}

function dbInsertId()
{
return mysql_insert_id();
}
//End DB functions


// setting up the web root and server root for
// this application
$thisFile = str_replace('\\', '/', __FILE__);
$docRoot = $_SERVER['DOCUMENT_ROOT'];

$webRoot  = str_replace(array($docRoot, 'functions.php'), '', $thisFile);
$srvRoot  = str_replace('functions.php', '', $thisFile);

define('WEB_ROOT', $webRoot);
define('SRV_ROOT', $srvRoot);

/*
Make sure each key name in $requiredField exist
in $_POST and the value is not empty
*/
function checkRequiredPost($requiredField) {
$numRequired = count($requiredField);
$keys        = array_keys($_POST);

$allFieldExist  = true;
for ($i = 0; $i < $numRequired && $allFieldExist; $i++) {
	if (!in_array($requiredField[$i], $keys) || $_POST[$requiredField[$i]] == '') {
		$allFieldExist = false;
	}
}

return $allFieldExist;
}

function queryString()
{
$qString = array();

foreach($_GET as $key => $value) {
	if (trim($value) != '') {
		$qString[] = $key. '=' . trim($value);
	} else {
		$qString[] = $key;
	}
}

$qString = implode('&', $qString);

return $qString;
}

/*
Put an error message on session 
*/
function setError($errorMessage)
{
if (!isset($_SESSION['cstock_error'])) {
	$_SESSION['cstock_error'] = array();
}

$_SESSION['cstock_error'][] = $errorMessage;

}

/*
print the error message
*/
function displayError()
{
if (isset($_SESSION['cstock_error']) && count($_SESSION['cstock_error'])) {
	$numError = count($_SESSION['cstock_error']);

	echo '<table id="errorMessage" width="550" align="center" cellpadding="20" cellspacing="0"><tr><td>';
	for ($i = 0; $i < $numError; $i++) {
		echo '&#8226; ' . $_SESSION['cstock_error'][$i] . "<br>\r\n";
	}
	echo '</td></tr></table>';

	// remove all error messages from session
	$_SESSION['cstock_error'] = array();
}
}


//User authentication functions
function checkUser()
{
// if the session id is not set, redirect to login page
if (!isset($_SESSION['cstockuserID'])) 
{
	header('Location: ' . WEB_ROOT . 'admin/login.php');
	exit;
}

//The user wishes to logout
if (isset($_GET['logout'])) 
{
	doLogout();
	exit;
}
}

function doLogout()
{
if (isset($_SESSION['cstockuserID'])) 
{
	unset($_SESSION['cstockuserID']);
	session_unregister('cstockuserID');
}

header('Location: index.php');
exit;
}

function doLogin()
{

$userName = $_POST['txtUserName'];
$password = $_POST['txtPassword'];

$sql = "SELECT UserID FROM cstockusers WHERE UserName = '$userName' AND Password = PASSWORD('$password')";
	$result = dbQuery($sql);

if (dbNumRows($result) == 1) 
{
	$row = dbFetchAssoc($result);
	$_SESSION['cstockuserID'] = $row['UserID'];

		// log the time when the user last logged in
		$sql = "UPDATE cstockusers SET LastLogin = NOW() WHERE UserID = '{$row['UserID']}'";
		dbQuery($sql);

		// now that the user is verified we move on to the next page
            // if the user had been in the admin pages before we move to
		// the last page visited
		if (isset($_SESSION['login_return_url'])) 
		{
			$errorMessage = 'This is the page you visited last';
			header('Location: ' . $_SESSION['login_return_url']);

			return $errorMessage;
			exit;
		} 
		else  
		{
			header('Location: index.php');
			exit;
		}
	}
	else 
	{
		$errorMessage = 'Wrong username or password. Please try again';
	}		

return $errorMessage;
}


//Pagination functions

function getPagingQuery($sql, $itemPerPage = 10)
{
if (isset($_GET['page']) && (int)$_GET['page'] > 0) 
{
	$page = (int)$_GET['page'];
} 
else 
{
	$page = 1;
}

// start fetching from this row number
$offset = ($page - 1) * $itemPerPage;

return $sql . " LIMIT $offset, $itemPerPage";
}

/*
Get the links to navigate between one result page to another.

*/
function getPagingLink($sql, $itemPerPage = 10, $strGet = '')
{
$result        = dbQuery($sql);
$pagingLink    = '';
$totalResults  = dbNumRows($result);
$totalPages    = ceil($totalResults / $itemPerPage);

// how many link pages to show
$numLinks      = 10;


// create the paging links only if theres more than one page of results
if ($totalPages > 1) {

	$self = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] ;


	if (isset($_GET['page']) && (int)$_GET['page'] > 0) {
		$pageNumber = (int)$_GET['page'];
	} else {
		$pageNumber = 1;
	}

	// print 'previous' link only if its not
	// on page one
	if ($pageNumber > 1) {
		$page = $pageNumber - 1;
		if ($page > 1) {
			$prev = " <a href=\"$self?page=$page&$strGet/\">[Prev]</a> ";
		} else {
			$prev = " <a href=\"$self?$strGet\">[Prev]</a> ";
		}	

		$first = " <a href=\"$self?$strGet\">[First]</a> ";
	} else {
		$prev  = ''; // on page one, don't show 'previous' link
		$first = ''; // nor 'first page' link
	}

	// print 'next' link only if its not
	// on the last page
	if ($pageNumber < $totalPages) {
		$page = $pageNumber + 1;
		$next = " <a href=\"$self?page=$page&$strGet\">[Next]</a> ";
		$last = " <a href=\"$self?page=$totalPages&$strGet\">[Last]</a> ";
	} else {
		$next = ''; // if on the last page, don't show 'next' link
		$last = ''; // nor 'last page' link
	}

	$start = $pageNumber - ($pageNumber % $numLinks) + 1;
	$end   = $start + $numLinks - 1;		

	$end   = min($totalPages, $end);

	$pagingLink = array();
	for($page = $start; $page <= $end; $page++)	{
		if ($page == $pageNumber) {
			$pagingLink[] = " $page ";   // no need to create a link to current page
		} else {
			if ($page == 1) {
				$pagingLink[] = " <a href=\"$self?$strGet\">$page</a> ";
			} else {	
				$pagingLink[] = " <a href=\"$self?page=$page&$strGet\">$page</a> ";
			}	
		}

	}

	$pagingLink = implode(' | ', $pagingLink);

	// return the page navigation link
	$pagingLink = $first . $prev . $pagingLink . $next . $last;
}

return $pagingLink;
}

?>

 

 

I call the pagination function in a page where I need to use it

 

Here is an example index page from my brands module (which is the default page of every module) It displays 5 items per page.

<?php
require_once '../../functions.php';

//$_SESSION['login_return_url'] = $_SERVER['REQUEST_URI'];
checkUser();
$view = (isset($_GET['view']) && $_GET['view'] != '') ? $_GET['view'] : '';

switch ($view) 
{
case 'list' :
	$content 	= 'list.php';		
	$pageTitle 	= 'Fragrance Lounge - Brand panel';
	break;

case 'modify' :
	$content 	= 'modify.php';		
	$pageTitle 	= 'Fragrance Lounge - Modify Brand';
	break;

case 'detail' :
	$content 	= 'detail.php';		
	$pageTitle 	= 'Fragrance Lounge - Showing Brand Details';
	break;

case 'showbybrand' :
	$content 	= 'showbybrand.php';		
	$pageTitle 	= 'Fragrance Lounge - Showing Brands By Brand';
break;

case 'showbycategory' :
	$content 	= 'showbycategory.php';		
	$pageTitle 	= 'Fragrance Lounge - Showing Brands By Category';
break;

case 'showbysearch' :
	$content 	= 'showbysearch.php';		
	$pageTitle 	= 'Fragrance Lounge - Showing Brands By Searching';
break;

	case 'choice' :
	if(isset($_POST["AddBrand"]) && trim($_POST["AddBrand"])!=='') 
		{
		$content 	= 'add.php';		
		$pageTitle 	= 'Fragrance Lounge - Add Brand';

		} 
	elseif(isset($_POST["DeleteBrand"]) && trim($_POST["DeleteBrand"])!=='') 
	{
	$content 	= 'delete.php';		
	$pageTitle 	= 'Fragrance Lounge - Delete Brand';
	}
break;
default :

	$content 	= 'list.php';		
	$pageTitle 	= 'Fragrance Lounge - Brand panel';
}

$script    = array('brand.js');

require_once '../include/template.php';
?>

 

The above index page displays (list.php) as its default page.

 

list.php below

 

<?php
if (!defined('WEB_ROOT')) {
exit;
}
$rowsPerPage = 5;

$sql = "SELECT * FROM cstockitems GROUP BY Brand";

$result     = dbQuery(getPagingQuery($sql, $rowsPerPage));
$pagingLink = getPagingLink($sql, $rowsPerPage);

?> 
<form action="index.php?view=choice" method="post"  name="frmList" id="frmList">
  <table width="100%" border="0" align="center" cellpadding="2" cellspacing="1">
    <tr class="title_text"> 
      <td width="400">Brand</td>
  <td width="400">Category</td>
      <td width="400">Date Created </td>
      <td width="200">View</td>
      <td width="200">Modify</td>
    </tr>
    <?php
if (dbNumRows($result) > 0) {
$i = 0;

while($row = dbFetchAssoc($result)) {
	extract($row);

	if ($i%2) {
		$class = 'row1';
	} else {
		$class = 'row2';
	}
	$i += 1;
?>
    <tr class="<?php echo $class; ?>"> 
      <td width="400"><?php echo $Brand; ?></td>
<td width="400"><?php echo $Category; ?></td>
      <td width="400"><?php echo $DateAddedBrand; ?></td>
      <td width="200"><a href="<?php echo $_SERVER['PHP_SELF']; ?>?view=detail&ProductID=<?php echo $ProductID; ?>">Details</a></td>
      <td width="200"><a href="javascript:modifyBrand(<?php echo $ProductID; ?>);">Modify</a></td>
    </tr>
    <?php
} // end while


?>
    <tr> 
      <td colspan="4" align="center"> 
        <?php 
   echo $pagingLink;
   ?>
      </td>
    </tr>
    <?php	
} else {
?>
    <tr> 
      <td colspan="4" align="center">No brands yet</td>
    </tr>
    <tr> 
      <td colspan="4" align="center"> </td>
    </tr>
    <?php
}
?>
    <tr> 
      <td colspan="4" align="right"> 
        <input name="AddBrand" type="submit" value="Add" class="button_image"> 
	<input type="submit" name="DeleteBrand" value="Delete" class="button_image">
    </tr>
  </table>
</form>
<label class="title_text">View available brands:</label>
<hr>
<table width="100%" border="0">
  <tr> 
    <td><form action="index.php?view=showbybrand" method="post" name="frmByBrand">
        <table width="100%" border="0">
          <tr> 
            <td width="200">By Brand:</td>
            <td width="200"><select name="sltBrand">
                <option value="0">Select Brand</option>
                <?
		$sql = "SELECT DISTINCT Brand FROM cstockitems ORDER BY Brand ASC";
		$result = dbQuery($sql);		

		if(dbNumRows($result))
		{
			while($row = dbFetchAssoc($result))
			{
			echo "<option>$row[brand]</option>";
			}
		}
		 		else 
				{
			echo "<option>No Brands Present</option>"; 
				}
  ?>
              </select></td>
            <td width="200"><input type="submit" name="Submit" value="Show" class="button_image" onClick="return CheckShowBrandByBrand();"> 
            </td>
          </tr>
        </table>
      </form></td>
  </tr>
  <tr> 
    <td><form name="frmByCategory" method="post" action="index.php?view=showbycategory">
        <table width="100%" border="0">
          <tr>
            <td width="200">By Category:</td>
            <td width="200"><select name="sltCategory">
                <option value="0">Select Category</option>
                <?
		$sql = "SELECT DISTINCT Category FROM cstockitems ORDER BY Category ASC";
		$result = dbQuery($sql);		

		if(dbNumRows($result))
		{
			while($row = dbFetchAssoc($result))
			{
			echo "<option>$row[Category]</option>";
			}
		}
		 		else 
				{
			echo "<option>No Categories Present</option>"; 
				}
  ?>
              </select></td>
            <td width="200"><input type="submit" name="Submit2" value="Show" class="button_image" onClick="return CheckShowBrandByCategory();"></td>
          </tr>
        </table>
      </form></td>
  </tr>
  <tr> 
    <td><form name="frmSearchBrand" method="post" action="index.php?view=showbysearch">
        <table width="100%" border="0">
          <tr>
            <td width="200">Search:</td>
            <td width="200"><input type="text" name="txtSearchBrand" size="40"></td>
            <td width="200"><input type="submit" name="Submit3" value="Search" class="button_image" onClick="return CheckShowBrandBySearch();"></td>
          </tr>
        </table>
      </form></td>
  </tr>
</table>

</body>
<script>
function CheckShowBrandByBrand()
{
form = window.document.frmByBrand;

if (form.sltBrand.selectedIndex == 0)
{
	alert('You have not selected a brand to view details!');
	return false;	
}
else
{
return true;
}
}

function CheckShowBrandByCategory()
{
form = window.document.frmByCategory;

if (form.sltCategory.selectedIndex == 0)
{
	alert('You have not selected a Category to view details!');
	return false;	
}
else
{
return true;
}
}

function CheckShowBrandBySearch()
{
form = window.document.frmSearchBrand;

if (form.txtSearchBrand.value == "")
{
	alert('You have not entered a brand name to search!');
	return false;	
}
else
{
return true;
}
}
</script>

 

My pagination works well here...

When I perform another action like a search from my index page, it displays the results well but when I click next or a number in the pagination, it goes to the default pagination of the (list.php) index page. ie It does not maintain the SQL condition of my search-It goes back to the SQL and code of list.php as above

<?
$rowsPerPage = 5;

$sql = "SELECT * FROM cstockitems GROUP BY Brand";

$result     = dbQuery(getPagingQuery($sql, $rowsPerPage));
$pagingLink = getPagingLink($sql, $rowsPerPage);
?>

 

HOW DO I MAKE MY PAGINATION WORK FOLLOWING THE SEARCH CONDITION AS FOLLOWS?

Below is my search code...

 

<?
require_once '../../functions.php';


$searchbrand = $_POST['txtSearchBrand'];

$sql = "SELECT * FROM cstockitems WHERE Category LIKE '%$searchbrand%' OR Brand LIKE '%$searchbrand%' ";
$rowsPerPage = 10;

$result     = dbQuery(getPagingQuery($sql, $rowsPerPage));
$pagingLink = getPagingLink($sql, $rowsPerPage);

?>
<form action="index.php?view=choice" method="post"  name="frmList" id="frmList">
  <table width="100%" border="0" align="center" cellpadding="2" cellspacing="1">
    <tr align="center" class="title_text"> 
      <td width="400" class="">Brand</td>
<td width="400" class="">Category</td>
      <td width="400">Date Created </td>
      <td width="200">View</td>
      <td width="200">Modify</td>
    </tr>
    <?php
if (dbNumRows($result) > 0) {
	$i = 0;

	while($row = dbFetchAssoc($result)) {
	extract($row);

	if ($i%2) {
		$class = 'row1';
	} else {
		$class = 'row2';
	}
	$i += 1;
?>
    <tr class="<?php echo $class; ?>"> 
      <td width="400"><?php echo $Brand; ?></td>
<td width="400"><?php echo $Category; ?></td>
      <td width="400"><?php echo $DateAddedBrand; ?></td>
      <td width="200" align="center"><a href="<?php echo $_SERVER['PHP_SELF']; ?>?view=detail&ProductID=<?php echo $ProductID; ?>">Details</a></td>
      <td width="200" align="center"><a href="javascript:modifyBrand(<?php echo $ProductID; ?>);">Modify</a></td>
    </tr>
    <?php
} // end while


?>
    <tr> 
      <td colspan="4" align="center"> 
        <?php 
   echo $pagingLink;
   ?>
      </td>
    </tr>
    <?php	
} else {
?>
    <tr> 
      <td colspan="4" align="center">Your search for <? echo '<strong>'; echo $searchbrand; echo ' '; echo "</strong>";  echo "did not return any brand(s)"; ?></td>
    </tr>
    <tr> 
      <td colspan="4" align="center"> </td>
    </tr>
    <?php
}
?>
    <tr> 
      <td colspan="4" align="right"> 
        <input name="AddBrand" type="submit" value="Add" class="button_image"> 
	<input type="submit" name="DeleteBrand" value="Delete" class="button_image">
	<input name="btnCancel" type="button" id="btnCancel" value="Back" onClick="window.location.href='index.php';" class="button_image">
    </tr>
  </table>
</form>

 

I hope it is clear and I provided enough information

 

 

 

 

Link to comment
Share on other sites

try

<?
require_once '../../functions.php';

$searchbrand = '';
if (isset($_POST['txtSearchBrand'])) $searchbrand = $_POST['txtSearchBrand'];
elseif (isset($_GET['s'])) $searchbrand = $_GET['s'];

$sql = "SELECT * FROM cstockitems WHERE Category LIKE '%$searchbrand%' OR Brand LIKE '%$searchbrand%' ";
$rowsPerPage = 10;

$result     = dbQuery(getPagingQuery($sql, $rowsPerPage));
$pagingLink = getPagingLink($sql, $rowsPerPage, "s=$searchbrand");

?>

etc.

 

 

Link to comment
Share on other sites

Sasa,

 

That was very close and quite genius.

 

I however still have the same problem.

The search is ok on the first page but the pagination goes back to the index.php (list.php) on subsequent paginations.

 

I really do not know why it does not maintain the search SQL statement.

 

I will be glad if you helped further.

 

Thanks.

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.