Applying Object-Oriented Programming in PHP Pagination

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.
  1. <?php
  2. //Database Constants
  3. defined('DB_SERVER') ? null : define("DB_SERVER","localhost");//define our database server
  4. defined('DB_USER') ? null : define("DB_USER","root"); //define our database user
  5. defined('DB_PASS') ? null : define("DB_PASS",""); //define our database Password
  6. defined('DB_NAME') ? null : define("DB_NAME","oracledbm"); //define our database Name
  7. ?>
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.
  1. <?php
  2.  
  3. require_once(LIB_PATH.DS."config.php");
  4. class Database {
  5. var $sql_string = '';
  6. var $error_no = 0;
  7. var $error_msg = '';
  8. private $conn;
  9. public $last_query;
  10. private $magic_quotes_active;
  11. private $real_escape_string_exists;
  12.  
  13. function __construct() {
  14. $this->open_connection();
  15. $this->magic_quotes_active = get_magic_quotes_gpc();
  16. $this->real_escape_string_exists = function_exists("mysql_real_escape_string");
  17. }
  18.  
  19. public function open_connection() {
  20. $this->conn = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
  21. if(!$this->conn){
  22. echo "Problem in database connection! Contact administrator!";
  23. exit();
  24. }else{
  25. $db_select = mysql_select_db(DB_NAME,$this->conn);
  26. if (!$db_select) {
  27. echo "Problem in selecting database! Contact administrator!";
  28. exit();
  29. }
  30. }
  31.  
  32. }
  33.  
  34. function setQuery($sql='') {
  35. $this->sql_string=$sql;
  36. }
  37.  
  38. function executeQuery() {
  39. $result = mysql_query($this->sql_string, $this->conn);
  40. $this->confirm_query($result);
  41. return $result;
  42. }
  43.  
  44. private function confirm_query($result) {
  45. if(!$result){
  46. $this->error_no = mysql_errno( $this->conn );
  47. $this->error_msg = mysql_error( $this->conn );
  48. return false;
  49. }
  50. return $result;
  51. }
  52.  
  53. function loadResultList( $key='' ) {
  54. $cur = $this->executeQuery();
  55.  
  56. $array = array();
  57. while ($row = mysql_fetch_object( $cur )) {
  58. if ($key) {
  59. $array[$row->$key] = $row;
  60. } else {
  61. $array[] = $row;
  62. }
  63. }
  64. return $array;
  65. }
  66.  
  67. function loadSingleResult() {
  68. $cur = $this->executeQuery();
  69.  
  70. while ($row = mysql_fetch_object( $cur )) {
  71. $data = $row;
  72. }
  73. return $data;
  74. }
  75.  
  76. function getFieldsOnOneTable( $tbl_name ) {
  77.  
  78. $this->setQuery("DESC ".$tbl_name);
  79. $rows = $this->loadResultList();
  80.  
  81. $f = array();
  82. for ( $x=0; $x<count( $rows ); $x++ ) {
  83. $f[] = $rows[$x]->Field;
  84. }
  85.  
  86. return $f;
  87. }
  88.  
  89. public function fetch_array($result) {
  90. return mysql_fetch_array($result);
  91. }
  92. //gets the number or rows
  93. public function num_rows($result_set) {
  94. return mysql_num_rows($result_set);
  95. }
  96.  
  97. public function insert_id() {
  98. // get the last id inserted over the current db connection
  99. return mysql_insert_id($this->conn);
  100. }
  101.  
  102. public function affected_rows() {
  103. return mysql_affected_rows($this->conn);
  104. }
  105.  
  106. public function escape_value( $value ) {
  107. if( $this->real_escape_string_exists ) { // PHP v4.3.0 or higher
  108. // undo any magic quote effects so mysql_real_escape_string can do the work
  109. if( $this->magic_quotes_active ) { $value = stripslashes( $value ); }
  110. $value = mysql_real_escape_string( $value );
  111. } else { // before PHP v4.3.0
  112. // if magic quotes aren't already on then add slashes manually
  113. if( !$this->magic_quotes_active ) { $value = addslashes( $value ); }
  114. // if magic quotes are active, then the slashes already exist
  115. }
  116. return $value;
  117. }
  118.  
  119. public function close_connection() {
  120. if(isset($this->conn)) {
  121. mysql_close($this->conn);
  122. unset($this->conn);
  123. }
  124. }
  125.  
  126. }
  127. $mydb = new Database();
  128.  
  129.  
  130. ?>
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.
  1. <?php
  2.  
  3.  
  4. //define the core paths
  5. //Define them as absolute paths to make sure that require_once works as expected
  6.  
  7. //DIRECTORY_SEPARATOR is a PHP Pre-defined constants:
  8. //(\ for windows, / for Unix)
  9. defined('DS') ? null : define('DS', DIRECTORY_SEPARATOR);
  10.  
  11. defined('SITE_ROOT') ? null : define ('SITE_ROOT', $_SERVER['DOCUMENT_ROOT'].DS.'pagination');
  12.  
  13. defined('LIB_PATH') ? null : define ('LIB_PATH',SITE_ROOT.DS.'includes');
  14.  
  15. // load config file first
  16. require_once(LIB_PATH.DS."config.php");
  17. //Load Core objects
  18. require_once(LIB_PATH.DS."database.php");
  19. require_once(LIB_PATH.DS."pagination.php");
  20.  
  21. //load database-related classes
  22. ?>
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.
  1. <?php
  2. require_once(LIB_PATH.DS.'database.php');
  3. class Helper {
  4.  
  5. protected static $tbl_name = "employees";
  6. public $current_page;
  7. public $per_page;
  8. public $total_count;
  9.  
  10. public function __construct($page=1, $per_page=20, $total_count=0){
  11. $this->current_page = (int)$page;
  12. $this->per_page = (int)$per_page;
  13. $this->total_count = (int)$total_count;
  14. }
  15.  
  16. function count_allemployees(){
  17. global $mydb;
  18. $mydb->setQuery("SELECT * FROM ".self::$tbl_name);
  19. $retval= $mydb->executeQuery();
  20. $total_count= $mydb->num_rows($retval);
  21. return $total_count;
  22. }
  23.  
  24. public function offset(){
  25. //get the off set current page minus 1 multiply by record per page
  26. return ($this->current_page - 1) * $this->per_page;
  27. }
  28.  
  29. public function total_pages(){
  30. //it gets the result of total_count over per page
  31. return ceil($this->total_count/$this->per_page);
  32. }
  33.  
  34. public function previous_page(){
  35. //move to previous record by subtracting one into the current record
  36. return $this->current_page - 1;
  37. }
  38. public function next_page(){
  39. //mvove to next record by incrementing the current page by one
  40. return $this->current_page + 1;
  41.  
  42. }
  43.  
  44. public function has_previous_page(){
  45. //check if previous record is still greater than one then it returns to true
  46. return $this->previous_page() >= 1 ? true : false;
  47. }
  48.  
  49. public function has_next_page(){
  50. //check if Next record is still lesser than one total pages then it returns to true
  51. return $this->next_page() <= $this->total_pages() ? true : false;
  52. }
  53.  
  54.  
  55. /*-Comon SQL Queries-*/
  56. function db_fields(){
  57. global $mydb;
  58. return $mydb->getFieldsOnOneTable(self::$tbl_name);
  59. }
  60.  
  61. /*---Instantiation of Object dynamically---*/
  62. static function instantiate($record) {
  63. $object = new self;
  64.  
  65. foreach($record as $attribute=>$value){
  66. if($object->has_attribute($attribute)) {
  67. $object->$attribute = $value;
  68. }
  69. }
  70. return $object;
  71. }
  72.  
  73. /*--Cleaning the raw data before submitting to Database--*/
  74. private function has_attribute($attribute) {
  75. // We don't care about the value, we just want to know if the key exists
  76. // Will return true or false
  77. return array_key_exists($attribute, $this->attributes());
  78. }
  79.  
  80. protected function attributes() {
  81. // return an array of attribute names and their values
  82. global $mydb;
  83. $attributes = array();
  84. foreach($this->db_fields() as $field) {
  85. if(property_exists($this, $field)) {
  86. $attributes[$field] = $this->$field;
  87. }
  88. }
  89. return $attributes;
  90. }
  91.  
  92. protected function sanitized_attributes() {
  93. global $mydb;
  94. $clean_attributes = array();
  95. // sanitize the values before submitting
  96. // Note: does not alter the actual value of each attribute
  97. foreach($this->attributes() as $key => $value){
  98. $clean_attributes[$key] = $mydb->escape_value($value);
  99. }
  100. return $clean_attributes;
  101. }
  102.  
  103.  
  104.  
  105. }
  106.  
  107. ?>
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:
  1. <?php require_once("includes/initialize.php");?>
  2. <!DOCTYPE html>
  3.  
  4. <html lang="en">
  5. <head>
  6. <meta charset="utf-8">
  7. <meta content="width=device-width, initial-scale=1.0" name="viewport">
  8. <meta content="" name="description">
  9. <meta content="" name="author">
  10. <link href="" rel="shortcut icon">
  11.  
  12. <title>Pagination</title><!-- Bootstrap core CSS -->
  13. <link href="css/bootstrap.css" rel="stylesheet">
  14. <link href="css/bootstrap-responsive.css" rel="stylesheet">
  15. </head>
  16.  
  17. <body>
  18. <div class="container">
  19. <div class="well">
  20. <h2>Pagination</h2>
  21. </div>
  22.  
  23. <div class="well">
  24. <table class="table table-condensed">
  25. <thead>
  26. <tr>
  27. <th>Employee ID</th>
  28. <th>Last Name</th>
  29. <th>First Name</th>
  30. <th>Email</th>
  31. <th>Salary</th>
  32. </tr>
  33. </thead>
  34.  
  35. <tbody>
  36. <?php
  37.  
  38. global $mydb;
  39.  
  40. //this is the current page per number ($current_page)
  41. $current_page = !empty($_GET['page']) ? (int)$_GET['page'] : 1;
  42.  
  43. //record per Page($per_page)
  44. $per_page = 5;
  45.  
  46. //total count record ($total_count)
  47. $countEmp = new Helper();
  48. $total_count = $countEmp->count_allemployees();
  49.  
  50. $pagination = new Helper($current_page, $per_page, $total_count);
  51.  
  52. //find records of employee and we specify the offset and the limit record per page
  53. $mydb->setQuery("SELECT employee_id, LAST_NAME, FIRST_NAME, EMAIL,
  54. salary FROM employees LIMIT {$pagination->per_page} OFFSET {$pagination->offset()}");
  55. $cur = $mydb->loadResultList();
  56. foreach($cur as $object){
  57. echo '<tr>';
  58. echo '<td>' . $object->employee_id . '</td>';
  59. echo '<td>' . $object->LAST_NAME . '</td>';
  60. echo '<td>' . $object->FIRST_NAME . '</td>';
  61. echo '<td>' . $object->EMAIL . '</td>';
  62. echo '<td>' . $object->salary . '</td>';
  63.  
  64. }
  65.  
  66. echo '</tr>';
  67. echo '</tbody>';
  68. echo '</table>';
  69.  
  70. echo '<ul class="pagination" align="center">';
  71.  
  72. if ($pagination->total_pages() > 1){
  73. //this is for previous record
  74. if ($pagination->has_previous_page()){
  75. echo ' <li><a href=advancePagination.php?page='.$pagination->previous_page().'>&laquo; </a> </li>';
  76. }
  77. //it loops to all pages
  78. for($i = 1; $i <= $pagination->total_pages(); $i++){
  79. //check if the value of i is set to current page
  80. if ($i == $pagination->current_page){
  81. //then it sset the i to be active or focused
  82. echo '<li class="active"><span>'. $i.' <span class="sr-only">(current)</span></span></li>';
  83. }else {
  84. //display the page number
  85. echo ' <li><a href=advancePagination.php?page='.$i.'> '. $i .' </a></li>';
  86. }
  87. }
  88. //this is for next record
  89. if ($pagination->has_next_page()){
  90. echo ' <li><a href=advancePagination.php?page='.$pagination->next_page().'>&raquo;</a></li> ';
  91. }
  92.  
  93. }
  94. ?>
  95. </tbody>
  96. </table>
  97. </div>
  98. </div>
  99. </body>
  100. </html>

Comments

Add new comment