November 10, 2008

Introduction to PEAR - Pager

Pagination is a frequent requirement in web development projects. Most PHP developers must have already implementated paging in one form or other in their projects. In this post we will see how to add pagination the easy way using PEAR’s Pager class. Use the following command to install the require library...

pear install Pager

Now you can use the class in your code as shown below:

/* Include the Pear::Pager file */
require_once ('Pager/Pager.php');

/* Replace this with your database details */
$connection = mysql_connect("localhost", "root", "");
mysql_select_db("calls", $connection);

/* First we need to get the total rows in the table */
$result=mysql_query("SELECT count(*) AS total FROM jaip2", $connection);
$row = mysql_fetch_array($result);

/* Total number of rows in the logs table */
$totalItems = $row['total'];

/* Set some options for the Pager */
$pager_options = array(
'mode' => 'Sliding', // Sliding or Jumping mode. See below.
'perPage' => 10, // Total rows to show per page
'delta' => 4, // See below
'totalItems' => $totalItems,
);

/* Initialize the Pager class with the above options */
$pager = Pager::factory($pager_options);

list($from, $to) = $pager->getOffsetByPageId();
/* The MySQL 'LIMIT' clause index starts from '0',
so decrease the $from by 1 */
$from = $from - 1;

/* The number of rows to get per query */
$perPage = $pager_options['perPage'];
echo "";
$result = mysql_query("SELECT id, inno FROM jaip2 LIMIT $from , $perPage", $connection);
while($row = mysql_fetch_array($result))
{
/* Do something with the query results */
echo "";
echo "";
echo "";
echo "";
}

echo "
".$row[0]."".$row[1]."
";

$topass = "select id, inno from jaip2 limit $from, $perPage";
$newpass = explode("limit", $topass);
$newsend = ($newpass[0]);
echo "

";
/* display the data */
echo $pager->links;
?>




As you can see the page has a link that says "Export to excel" and calls the page testexport.php page. The source code of that page is given below...

/* Replace this with your database details */
$connection = mysql_connect("localhost", "root", "");
mysql_select_db("calls", $connection);

$string = $_GET["toimport"];

$result = mysql_query("$string", $connection);

$tsv = array();
$html = array();

while($row = mysql_fetch_array($result, MYSQL_NUM))
{
$tsv[] = implode("\t", $row);
$html[] = "" .implode("", $row) . "";
}

$tsv = implode("\r\n", $tsv);
$html = "" . implode("\r\n", $html) . "
";

$fileName = 'mysql-to-excel.xls';
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$fileName");

echo $tsv;

// echo $html;

?>


Read more...

http://www.codediesel.com/php/simple-pagination-in-php/

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.