This tutorial is a continuation of our previous tutorial called “
PHP Pagination”. At this time we’re going to focus on how to perform Pagination using Object-oriented Programming in PHP. Using this OOP we can minimize our code in creating a PHP pagination in our all web pages especially when we are developing a big system. To start with this application, open our file in the document root called “pagination”. Then, we are going to create a new folder called includes. And inside this directory, we need to create some PHP files and these are: config.php, database.php, initialize.php and pagination.php.
In the config.php file, add the following code:
This code below, we simply declare our database constants such as our database server, user and Database name.
<?php
//Database Constants
defined('DB_SERVER') ?
null : define("DB_SERVER","localhost");//define our database server
defined('DB_USER') ?
null : define("DB_USER","root"); //define our database user
defined('DB_PASS') ?
null : define("DB_PASS",""); //define our database Password
defined('DB_NAME') ?
null : define("DB_NAME","oracledbm"); //define our database Name
?>
And for the database.php file, add the following code:
This code below is a class for a database that supports both traditional structures and active record patterns. And this class will handle all the database objects.
<?php
require_once(LIB_PATH.DS."config.php");
class Database {
var $sql_string = '';
var $error_no = 0;
var $error_msg = '';
private $conn;
public $last_query;
private $magic_quotes_active;
private $real_escape_string_exists;
function __construct() {
$this->open_connection();
$this->real_escape_string_exists = function_exists("mysql_real_escape_string");
}
public function open_connection() {
if(!$this->conn){
echo "Problem in database connection! Contact administrator!";
}else{
if (!$db_select) {
echo "Problem in selecting database! Contact administrator!";
}
}
}
function setQuery($sql='') {
$this->sql_string=$sql;
}
function executeQuery() {
$this->confirm_query($result);
return $result;
}
private function confirm_query($result) {
if(!$result){
return false;
}
return $result;
}
function loadResultList( $key='' ) {
$cur = $this->executeQuery();
if ($key) {
$array[$row->$key] = $row;
} else {
$array[] = $row;
}
}
return $array;
}
function loadSingleResult() {
$cur = $this->executeQuery();
$data = $row;
}
return $data;
}
function getFieldsOnOneTable( $tbl_name ) {
$this->setQuery("DESC ".$tbl_name);
$rows = $this->loadResultList();
for ( $x=0; $x<count( $rows ); $x++ ) {
$f[] = $rows[$x]->Field;
}
return $f;
}
public function fetch_array($result) {
}
//gets the number or rows
public function num_rows($result_set) {
}
public function insert_id() {
// get the last id inserted over the current db connection
}
public function affected_rows() {
}
public function escape_value( $value ) {
if( $this->real_escape_string_exists ) { // PHP v4.3.0 or higher
// undo any magic quote effects so mysql_real_escape_string can do the work
if( $this->magic_quotes_active ) { $value = stripslashes( $value ); }
} else { // before PHP v4.3.0
// if magic quotes aren't already on then add slashes manually
if( !$this->magic_quotes_active ) { $value = addslashes( $value ); }
// if magic quotes are active, then the slashes already exist
}
return $value;
}
public function close_connection() {
}
}
}
$mydb = new Database();
?>
Next for the initialize.php, add the following code:
The code below is used to initialize all configurations and database related objects and this is useful because we don’t need to include or require or other PHP file in all our web pages from our web directory.
<?php
//define the core paths
//Define them as absolute paths to make sure that require_once works as expected
//DIRECTORY_SEPARATOR is a PHP Pre-defined constants:
//(\ for windows, / for Unix)
defined('SITE_ROOT') ?
null : define ('SITE_ROOT', $_SERVER['DOCUMENT_ROOT'].DS
.'pagination');
defined('LIB_PATH') ?
null : define ('LIB_PATH',SITE_ROOT
.DS
.'includes');
// load config file first
require_once(LIB_PATH.DS."config.php");
//Load Core objects
require_once(LIB_PATH.DS."database.php");
require_once(LIB_PATH.DS."pagination.php");
//load database-related classes
?>
And for the pagination.php, add the following code:
This pagination.php file will serve as a helper that save us from more ground work out of doing pagination.
<?php
require_once(LIB_PATH.DS.'database.php');
class Helper {
protected static $tbl_name = "employees";
public $current_page;
public $per_page;
public $total_count;
public function __construct($page=1, $per_page=20, $total_count=0){
$this->current_page = (int)$page;
$this->per_page = (int)$per_page;
$this->total_count = (int)$total_count;
}
function count_allemployees(){
global $mydb;
$mydb->setQuery("SELECT * FROM ".self::$tbl_name);
$retval= $mydb->executeQuery();
$total_count= $mydb->num_rows($retval);
return $total_count;
}
public function offset(){
//get the off set current page minus 1 multiply by record per page
return ($this->current_page - 1) * $this->per_page;
}
public function total_pages(){
//it gets the result of total_count over per page
return ceil($this->total_count/$this->per_page);
}
public function previous_page(){
//move to previous record by subtracting one into the current record
return $this->current_page - 1;
}
public function next_page(){
//mvove to next record by incrementing the current page by one
return $this->current_page + 1;
}
public function has_previous_page(){
//check if previous record is still greater than one then it returns to true
return $this->previous_page() >= 1 ? true : false;
}
public function has_next_page(){
//check if Next record is still lesser than one total pages then it returns to true
return $this->next_page() <= $this->total_pages() ? true : false;
}
/*-Comon SQL Queries-*/
function db_fields(){
global $mydb;
return $mydb->getFieldsOnOneTable(self::$tbl_name);
}
/*---Instantiation of Object dynamically---*/
static function instantiate($record) {
$object = new self;
foreach($record as $attribute=>$value){
if($object->has_attribute($attribute)) {
$object->$attribute = $value;
}
}
return $object;
}
/*--Cleaning the raw data before submitting to Database--*/
private function has_attribute($attribute) {
// We don't care about the value, we just want to know if the key exists
// Will return true or false
}
protected function attributes() {
// return an array of attribute names and their values
global $mydb;
foreach($this->db_fields() as $field) {
if(property_exists($this, $field)) {
$attributes[$field] = $this->$field;
}
}
return $attributes;
}
protected function sanitized_attributes() {
global $mydb;
$clean_attributes = array();
// sanitize the values before submitting
// Note: does not alter the actual value of each attribute
foreach($this->attributes() as $key => $value){
$clean_attributes[$key] = $mydb->escape_value($value);
}
return $clean_attributes;
}
}
?>
At this time we need to create a new PHP file called advancePagination.php and will place it in our document root. And add the following code:
<?php require_once("includes/initialize.php");?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<meta content="" name="description">
<meta content="" name="author">
<link href="" rel="shortcut icon">
<title>Pagination</title><!-- Bootstrap core CSS -->
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/bootstrap-responsive.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="well">
<h2>Pagination</h2>
</div>
<div class="well">
<table class="table table-condensed">
<thead>
<tr>
<th>Employee ID</th>
<th>Last Name</th>
<th>First Name</th>
<th>Email</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<?php
global $mydb;
//this is the current page per number ($current_page)
$current_page = !empty($_GET['page']) ?
(int
)$_GET['page'] : 1;
//record per Page($per_page)
$per_page = 5;
//total count record ($total_count)
$countEmp = new Helper();
$total_count = $countEmp->count_allemployees();
$pagination = new Helper($current_page, $per_page, $total_count);
//find records of employee and we specify the offset and the limit record per page
$mydb->setQuery("SELECT employee_id, LAST_NAME, FIRST_NAME, EMAIL,
salary FROM employees LIMIT {$pagination->per_page} OFFSET {$pagination->offset()}");
$cur = $mydb->loadResultList();
foreach($cur as $object){
echo '<tr>';
echo '<td>' . $object->employee_id . '</td>';
echo '<td>' . $object->LAST_NAME . '</td>';
echo '<td>' . $object->FIRST_NAME . '</td>';
echo '<td>' . $object->EMAIL . '</td>';
echo '<td>' . $object->salary . '</td>';
}
echo '</tr>';
echo '</tbody>';
echo '</table>';
echo '<ul class="pagination" align="center">';
if ($pagination->total_pages() > 1){
//this is for previous record
if ($pagination->has_previous_page()){
echo ' <li><a href=advancePagination.php?page='.$pagination->previous_page().'>« </a> </li>';
}
//it loops to all pages
for($i = 1; $i <= $pagination->total_pages(); $i++){
//check if the value of i is set to current page
if ($i == $pagination->current_page){
//then it sset the i to be active or focused
echo '<li class="active"><span>'. $i.' <span class="sr-only">(current)</span></span></li>';
}else {
//display the page number
echo ' <li><a href=advancePagination.php?page='.$i.'> '. $i .' </a></li>';
}
}
//this is for next record
if ($pagination->has_next_page()){
echo ' <li><a href=advancePagination.php?page='.$pagination->next_page().'>»</a></li> ';
}
}
?>
</tbody>
</table>
</div>
</div>
</body>
</html>