Jump to content

Recommended Posts

I am using both an ajax live search and pagination. The ajax part works fine but due to unwieldy data, the live search started crashing browsers or just took to long to load. Thus I needed to paginate. This is where the problems started to occur. I attached all the files just in case anyone wanted to take a closer look at it. Okay, so lets start with the problem. When I try to paginate the very first page comes up fine. However when I click the link to go to the next page, the results are incorrect and spurious, not to mention the variable that holds the form GET info get lost and an undefined variable error occurs and last but not least I want the user to remain on traveller.php and not go to usage.php. The links send you to usage.php page. This is the code for the page where the live search is done. The name of this page is traveller.php

<html>
<head>
<title>Testing</title>
<script src="traveller.js"></script>
</head>
<body>
<form>
<input type="text" id="users" size="30"
onkeyup="showResult(this.value)">
</form>

<p>
<div id="livesearch">

</div>
</body>
</html>

You would notice that the ajax runs in a separate file called traveller.js. Here is the code

// JavaScript Document
var xmlHttp

function showResult(str)
{
if (str.length==0)
{ 
document.getElementById("livesearch").
innerHTML="";
document.getElementById("livesearch").
style.border="0px";
return
}

xmlHttp=GetXmlHttpObject()

if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
} 

[color=red]var url="usage.php"[/color]
url=url+"?q="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged 
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
} 

function stateChanged() 
{ 
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{ 
document.getElementById("livesearch").
innerHTML=xmlHttp.responseText;
document.getElementById("livesearch").
style.border="1px solid #A5ACB2";
} 
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
  {
  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
catch (e)
  {
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
}
return xmlHttp;
}

The only part in this file that needs editing, I have highlighted. var url="usage.php".  ???You have to insert the name of the php paage that's processing the MySQL data and returning the results. Now for the page that does some of the processing. Its called usage.php

//Include the PS_Pagination class
include('ps_pagination.php');

$q = $_GET["q"];


//Connect to mysql db
$conn = mysql_connect('localhost','username','password');
mysql_select_db('apis_live',$conn);
$sql = "SELECT TRAVELLER_PKEY, FIRSTNAME, LASTNAME, MIDDLENAME FROM traveller WHERE FIRSTNAME like '".$q."%' OR LASTNAME like '".$q."%' OR MIDDLENAME like '".$q."%'";




//Create a PS_Pagination object
$pager = new PS_Pagination($conn,$sql,20,20);



//The paginate() function returns a mysql result set 
$rs = $pager->paginate();



echo "<table border='1'>
<tr>
<th>Details</th>
<th>First Name</th>
<th>Middle Name</th>
<th>Last Name</th>
</tr>";
while($row = mysql_fetch_assoc($rs)) {
	echo "<tr>";
	 echo "<td><a href='traveller-details.php?id=" .$row['TRAVELLER_PKEY']."'>Details</a></td>";
	 echo "<td>" . $row['FIRSTNAME'] . "</td>";
	 echo "<td>" . $row['MIDDLENAME'] . " </td>";
	 echo "<td>" . $row['LASTNAME'] . "</td>";
	 echo "</tr>";
}

echo "</table>";

//Display the full navigation in one go
echo $pager->renderFullNav();

As you can see this page refers to another page that creates all the objects. That page is called ps_pagination, and here is the code:

class PS_Pagination {
var $php_self;
var $rows_per_page; //Number of records to display per page
var $total_rows; //Total number of rows returned by the query
var $links_per_page; //Number of links to display per page
var $sql;
var $debug = false;
var $conn;
var $page;
var $max_pages;
var $offset;


/**
 * Constructor
 *
 * @param resource $connection Mysql connection link
 * @param string $sql SQL query to paginate. Example : SELECT * FROM users
 * @param integer $rows_per_page Number of records to display per page. Defaults to 10
 * @param integer $links_per_page Number of links to display per page. Defaults to 5
 */



function PS_Pagination($connection, $sql, $q, $rows_per_page = 20, $links_per_page = 10) {
	$this->conn = $connection;
	$this->sql = $sql;
	$this->rows_per_page = $rows_per_page;
	$this->links_per_page = $links_per_page;
	$this->php_self = htmlspecialchars($_SERVER['PHP_SELF']);
	if(isset($_GET['page'])) {
		$this->page = intval($_GET['page']);
	}
}

/**
 * Executes the SQL query and initializes internal variables
 *
 * @access public
 * @return resource
 */
function paginate() {
	if(!$this->conn) {
		if($this->debug) echo "MySQL connection missing<br />";
		return false;
	}

	$all_rs = @mysql_query($this->sql);
	if(!$all_rs) {
		if($this->debug) echo "SQL query failed. Check your query.<br />";
		return false;
	}
	$this->total_rows = mysql_num_rows($all_rs);
	@mysql_close($all_rs);

	$this->max_pages = ceil($this->total_rows/$this->rows_per_page);
	//Check the page value just in case someone is trying to input an aribitrary value
	if($this->page > $this->max_pages || $this->page <= 0) {
		$this->page = 1;
	}

	//Calculate Offset
	$this->offset = $this->rows_per_page * ($this->page-1);

	//Fetch the required result set
	$rs = @mysql_query($this->sql." LIMIT {$this->offset}, {$this->rows_per_page}");
	if(!$rs) {
		if($this->debug) echo "Pagination query failed. Check your query.<br />";
		return false;
	}
	return $rs;
}

/**
 * Display the link to the first page
 *
 * @access public
 * @param string $tag Text string to be displayed as the link. Defaults to 'First'
 * @return string
 */
function renderFirst($tag='First') {
	if($this->page == 1) {
		return $tag;
	}
	else {
		return '<a href="'.$this->php_self.'?page=1">'.$tag.'</a>';
	}
}

/**
 * Display the link to the last page
 *
 * @access public
 * @param string $tag Text string to be displayed as the link. Defaults to 'Last'
 * @return string
 */
function renderLast($tag='Last') {
	if($this->page == $this->max_pages) {
		return $tag;
	}
	else {
		return '<a href="'.$this->php_self.'?page='.$this->max_pages.'">'.$tag.'</a>';
	}
}

/**
 * Display the next link
 *
 * @access public
 * @param string $tag Text string to be displayed as the link. Defaults to '>>'
 * @return string
 */
function renderNext($tag=' >>') {
	if($this->page < $this->max_pages) {
		return '<a href="'.$this->php_self.'?page='.($this->page+1).'">'.$tag.'</a>';
	}
	else {
		return $tag;
	}
}

/**
 * Display the previous link
 *
 * @access public
 * @param string $tag Text string to be displayed as the link. Defaults to '<<'
 * @return string
 */
function renderPrev($tag='<<') {
	if($this->page > 1) {
		return '<a href="'.$this->php_self.'?page='.($this->page-1).'">'.$tag.'</a>';
	}
	else {
		return $tag;
	}
}

/**
 * Display the page links
 *
 * @access public
 * @return string
 */
function renderNav() {
	for($i=1;$i<=$this->max_pages;$i+=$this->links_per_page) {
		if($this->page >= $i) {
			$start = $i;
		}
	}

	if($this->max_pages > $this->links_per_page) {
		$end = $start+$this->links_per_page;
		if($end > $this->max_pages) $end = $this->max_pages+1;
	}
	else {
		$end = $this->max_pages;
	}

	$links = '';

	for( $i=$start ; $i<$end ; $i++) {
		if($i == $this->page) {
			$links .= " $i ";
		}
		else {
			$links .= ' <a href="'.$this->php_self.'?page='.$i.'">'.$i.'</a> ';
		}
	}

	return $links;
}

/**
 * Display full pagination navigation
 *
 * @access public
 * @return string
 */
function renderFullNav() {
	return $this->renderFirst().' '.$this->renderPrev().' '.$this->renderNav().' '.$this->renderNext().' '.$this->renderLast();	
}

/**
 * Set debug mode
 *
 * @access public
 * @param bool $debug Set to TRUE to enable debug messages
 * @return void
 */
function setDebug($debug) {
	$this->debug = $debug;
}
}

FYI this pagination came from the internet and there is no copyright problem in using it. Here is the link for the original script:

http://phpsense.com/php/php-pagination-script.html . Last but not least, as I said when I try to go the next paginated page the results get skewed and there is an error at the top of the page that says:

Notice: Undefined index: q in C:\apache\Apache2\htdocs\testing\usage.php on line 5 

Line 5 is this:

$q = $_GET["q"];

I know this is a huge one but I am hoping someone could help me.

 

[attachment deleted by admin]

Link to comment
https://forums.phpfreaks.com/topic/157877-huge-pagination-problem/
Share on other sites

gevans, what's else $q for?

 

Though he should never get that far with an empty string, he is using $q further in the script after what seems like an unset GET variable. So if he does want to do it this way (which I'm not saying is right) by checking that $_GET['q'] is set you can assign it to $q, if it isn't set you still need to declare the variable otherwise the script will throw an error when trying to use $q later.

 

Having $q in the script is just setting it to a NULL value.

I thank you for the very swift response and something similar I did do and it has solved the problem of the "undefined" variable. Having said that lets get straight into it. Remember, for now I am interested in what works, I'll go back and clean up according to rules etc once it runs. Here is the new code for usage.php

//Include the PS_Pagination class
include('ps_pagination.php');


if(!isset($_GET["q"]))
{
$q = $_GET["q"];
}
else 
{
$q=$_GET["q"];
}



//Connect to mysql db
$conn = mysql_connect('localhost','root','newman$');
mysql_select_db('apis_live',$conn);
$sql = "SELECT TRAVELLER_PKEY, FIRSTNAME, LASTNAME, MIDDLENAME FROM traveller WHERE FIRSTNAME like '".$q."%' OR LASTNAME like '".$q."%' OR MIDDLENAME like '".$q."%'";

I did not paste the entire thing just the part that changes. Everything else is the same. I also had to change ps_pagination.php. In order for the new code to work with $q I had to include it in the url of the "next" page links. Thus the adjustments are as follows:

function renderLast($tag='Last') {
	if($this->page == $this->max_pages) {
		return $tag;
	}
	else {
		return '<a href="'.$this->php_self.'?page='.$this->max_pages.'&q='.$_GET["q"].'">'.$tag.'</a>';
	}
}

/**
 * Display the next link
 *
 * @access public
 * @param string $tag Text string to be displayed as the link. Defaults to '>>'
 * @return string
 */
function renderNext($tag=' >>') {
	if($this->page < $this->max_pages) {
		return '<a href="'.$this->php_self.'?page='.($this->page+1).'&q='.$_GET["q"].'">'.$tag.'</a>';
	}
	else {
		return $tag;
	}
}

/**
 * Display the previous link
 *
 * @access public
 * @param string $tag Text string to be displayed as the link. Defaults to '<<'
 * @return string
 */
function renderPrev($tag='<<') {
	if($this->page > 1) {
		return '<a href="'.$this->php_self.'?page='.($this->page-1).'&q='.$_GET["q"].'">'.$tag.'</a>';
	}
	else {
		return $tag;
	}
}

/**
 * Display the page links
 *
 * @access public
 * @return string
 */
function renderNav() {
	for($i=1;$i<=$this->max_pages;$i+=$this->links_per_page) {
		if($this->page >= $i) {
			$start = $i;
		}
	}

	if($this->max_pages > $this->links_per_page) {
		$end = $start+$this->links_per_page;
		if($end > $this->max_pages) $end = $this->max_pages+1;
	}
	else {
		$end = $this->max_pages;
	}

	$links = '';

	for( $i=$start ; $i<$end ; $i++) {
		if($i == $this->page) {
			$links .= " $i ";
		}
		else {
			$links .= ' <a href="'.$this->php_self.'?page='.$i.'&q='.$_GET["q"].'">'.$i.'</a> ';
		}
	}

	return $links;
}

/**
 * Display full pagination navigation
 *
 * @access public
 * @return string
 */
function renderFullNav() {
	return $this->renderFirst().' '.$this->renderPrev().' '.$this->renderNav().' '.$this->renderNext().' '.$this->renderLast();	
}

/**
 * Set debug mode
 *
 * @access public
 * @param bool $debug Set to TRUE to enable debug messages
 * @return void
 */
function setDebug($debug) {
	$this->debug = $debug;
}
}

Notice the $_GET["q"] that is now in the links. So just ONE more problem to solve. Those said links when clicked, instead of keeping me on traveller.php I go to usage.php. Even though the very first result show properly in traveller.php, the moment I try to veiw any other page I go to usage.php and so the data is correct but I lost all my markup and fancy layout. I may drop the ajax all together and just use a simple form and use a "get" method. This app is strictly internal so security is not that big an issue. Sill would like a solution with the Ajax, not giving up just yet. I appreciate the response.

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.