این بخش آموزشی ادامه ی بخش آموزشی قبلیمان تحت عنوان صفحه بندی PHP است. اینبار میخواهیم بر روی چگونگی اجرای صفحه بندی با استفاده از برنامه نویسی شئ گرا در PHP تمرکز کنیم. با استفاده از این OOP میتوانیم کد هایمان را در ساخت یک صفحه بندی PHP در تمام صفحه های وب مان کوچک کنیم به خصوص زمانی که در حال توسعه ی یک سیستم بزرگ هستیم.
برای شروع این برنامه فایلمان در سندی بنام “Pagination” را باز میکنیم. سپس میخواهیم یک فولدر جدید بنام includes بسازیم. و در داخل این راهنما ما نیاز به ساخت چند فایل PHP داریم و این ها شامل : config.php , database.php , initialize .php و pagination.php .
در فایل config.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 ?>
و برای فایل database.php کد های زیر را وارد کنید :
این کد زیر یک کلاس برای پایگاه داده است که که از ساختار های مرسوم و الگو های سوابق فعال پشتیبانی میکند و این کلاس تمام اشیای پایگاه داده را کنترل میکند.
<?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->magic_quotes_active = get_magic_quotes_gpc(); $this->real_escape_string_exists = function_exists("mysql_real_escape_string"); } public function open_connection() { $this->conn = mysql_connect(DB_SERVER,DB_USER,DB_PASS); if(!$this->conn){ echo "Problem in database connection! Contact administrator!"; exit(); }else{ $db_select = mysql_select_db(DB_NAME,$this->conn); if (!$db_select) { echo "Problem in selecting database! Contact administrator!"; exit(); } } } function setQuery($sql='') { $this->sql_string=$sql; } function executeQuery() { $result = mysql_query($this->sql_string, $this->conn); $this->confirm_query($result); return $result; } private function confirm_query($result) { if(!$result){ $this->error_no = mysql_errno( $this->conn ); $this->error_msg = mysql_error( $this->conn ); return false; } return $result; } function loadResultList( $key='' ) { $cur = $this->executeQuery(); $array = array(); while ($row = mysql_fetch_object( $cur )) { if ($key) { $array[$row->$key] = $row; } else { $array[] = $row; } } mysql_free_result( $cur ); return $array; } function loadSingleResult() { $cur = $this->executeQuery(); while ($row = mysql_fetch_object( $cur )) { $data = $row; } mysql_free_result( $cur ); return $data; } function getFieldsOnOneTable( $tbl_name ) { $this->setQuery("DESC ".$tbl_name); $rows = $this->loadResultList(); $f = array(); for ( $x=0; $x<count( $rows ); $x++ ) { $f[] = $rows[$x]->Field; } return $f; } public function fetch_array($result) { return mysql_fetch_array($result); } //gets the number or rows public function num_rows($result_set) { return mysql_num_rows($result_set); } public function insert_id() { // get the last id inserted over the current db connection return mysql_insert_id($this->conn); } public function affected_rows() { return mysql_affected_rows($this->conn); } 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 ); } $value = mysql_real_escape_string( $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() { if(isset($this->conn)) { mysql_close($this->conn); unset($this->conn); } } } $mydb = new Database(); ?>
سپس برای initialize.php کد زیر را بیافزایید :
کد زیر برای مقداردهی اولیه تمام پیکربندی ها و پایگاه داده ی اشیای مرتبط و این مفید خواهد بود زیرا ما نیازی به include یا require و یا هر فایل PHP دیگری در همه ی صفحات وب مان در راهنمای وب مان نداریم.
<?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('DS') ? null : define('DS', DIRECTORY_SEPARATOR); 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 ?>
و برای pagination.php کد زیر را اضافه کنید :
این فایل pagination.php به عنوان یک کمک کننده است که ما را از کار های دستی صفحه بندی بیشتر حفظ میکند.
<?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 return array_key_exists($attribute, $this->attributes()); } protected function attributes() { // return an array of attribute names and their values global $mydb; $attributes = array(); 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; } } ?>
حال ما نیاز داریم که یک فایل PHP جدید به نام advancePagination.php بسازیم و آن را در ریشه ی اسنادمان بگذاریم و کد زیر را اضافه کنیم :
<?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>
هیچ دیدگاهی نوشته نشده است.