Pagination with PHP OOP system #1 Basic OOP Class, Fetch data with PDO Database, Use Function in a Class

in #utopian-io7 years ago (edited)

Repository

https://github.com/php/php-src

What Will I Learn?

  • Basic OOP Class
  • Use Function in a Class
  • Database PDO, Connection, Query

Requirements

  • Basic HTML
  • Basic OOP
  • Basic Sql Query
  • Localhost (xampp, wampp, or etc)
  • PHP >= 5.6

Difficulty

  • Intermediate

Tutorial Contents

In this tutorial, we will learn how to create pagination with PHP OOP system. by using OOP we will create many Classes and functions that will make this pagination system to be dynamic and does not apply to certain data only.

Preparation

I will create a project folder with the name pagination and create a folder inside. The folder name is class and create a file index.php. I will also create a database to use to create pagination.

  • Create database
    The database name is faker and its table name is users. I will use faker to get dummy data. You can use dummy data for your database, please visit https://github.com/fzaninotto/Faker.

  • The structure of table users

NameTypeLength/valueIndeks
idINT11Primary
usernameVarchar100--
cityVarchar100--
emailVarchar100--


Screenshot_4.png

Create pagination{} class

We will create the class Pagination{} and in the Pagination class, we will create some variables whose contents will often be used.

  • Variable declaration

Example:

<?php 
    class Pagination{
        private $db, $table, $total_records, $limit = 5;
    }
 ?>
  • In the class pagination I will create some variables to store data that will be used frequently.
    1. $db: This variable will save the connection to the database.
    2. $table: This variable will be the parameter of the table name that will be used.
    3. $total_records: This variable will store the total amount of data in the database.
    4. $limit = 5: This variable will be the reference amount of data to be displayed on each page. The value is 5.

  • Create __construct (){} function
    Example:
<?php 
    class Pagination{
        private $db, $table, $total_records, $limit = 5;
        //PDO connection
        public function __construct($table){
            $this->table = $table;
            $this->db = new PDO("mysql:host=localhost; dbname=faker", "root", "root");
            $this->set_total_records();
        }
    }
 ?>
  • We will create a function __construct(){}. __construct() will be run the first time the function is created. I will explain what will be run in the function __construct ():
    1. $this->table = $table; : assigns a value to the variable $table with the value we get from the parameters in the function __contruct ($table).
    2. Connection to the PDO database : We can connect to PDO database with new PDO () method and we can save these connections into variables that have been declared above $this->db.
    Example:

new PDO("databaseDriver:host=localhost; dbname=databaseName", "username", "password");

3. Call function set_total_records (): We need to get the amount of data in the database for us to use as a reference number of pages to be displayed. function set_total_records () is created outside the function __construct ().

  • Create set_total_records(){} function
    Example:
<?php 
    class Pagination{
        public function set_total_records(){
            $stmt   = $this->db->prepare("SELECT id FROM $this->table");
            $stmt->execute();
            $this->total_records = $stmt->rowCount();
        }
    }
 ?>
  • We use the PDO database to make the Query SQL. We can use the prepare () and to run the query we can use execute (). I made a simple query "SELECT id FROM $this->table" to retrieve the id from the 'users' table and do count with rowCount (). $this->table is a variable that has been assigned a value in the function __construct() and then we save the result of the sum in the variable $total_records.

Noted: We can access the variables inside the function by using $this.

  • Create current_page(){} function
    We can detect the current page through the parameter query, ?page=pageNumber. We can detect via isset() method and then we can do logic to make the value 1 as a minimum number of pages. statement ? if true : if false. This function only returns the value of the page. This function returns value of the page we will use in the get_data()

Example:

public function current_page(){
            return isset($_GET['page']) ? (int)$_GET['page'] :1;
        }


  • Create get_data(){} function
    We will retrieve data from database via function get_data ().

Example:

public function get_data(){
            $start = 0;
            if($this->current_page() > 1){
                $start = ($this->current_page() * $this->limit) - $this->limit;
            }
            $stmt = $this->db->prepare("SELECT * FROM $this->table LIMIT $start, $this->limit");
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_OBJ);
        }
  • We will check if the current page is larger than > 1. We can get the value of current page via $this->current_page(). if $this->current_page() > 1 then we will do the math operation ($this->current_page() * $this->limit) - $this->limit; and We will store the value in $start as a reference starting from the order in which we get the data in the database..

  • Then we can do the a query with SELECT * FROM $this->table LIMIT $start, $this->limit. it's means SELECT * FROM tableName LIMIT startFrom, limit

  • And we can return data with object type fetchAll(PDO::FETCH_OBJ)

  • Create get_pagination_number(){} function
    to display the index page. we can create the following function:

Example:

public function get_pagination_number(){
            return ceil($this->total_records / $this->limit);
        }
  • This function ceil() the result of the division between the amount of data$this->total_records and the limit $this->limit. $this->total_records is a variable whose value has been assigned when the __construct () function is executed. $this->limit is a variable that we have assigned with value 5.

Using pagination{} class

We have made the functions in the pagination class, now we will see the usefulness of each of these functions.

  • get_data ()

We have finished creating the pagination{} class. Now we can already use it in index.php.

<?php 
    require_once 'class/Pagination.php';
    $pagination  = new Pagination('users');
    $users = $pagination->get_data();
    var_dump($users);
?>
  • We import the pagination class with require_once 'class/Pagination.php'. adjust to your file directory.

  • We initialize the new class on the $pagination variable and we passed the 'users' parameter. This parameter will be accepted by __construct () and used as table name. adjust the table name in your database with this parameter.

  • We have created get_data () function in the previous section. We have initialized the class pagination inside the $pagination variable.Now we can use it like this $pagination->get_data(). then we save the result in variable $users and I will var_dump() to see the data in browser.

  • The Result

Screenshot_6.png

  • Use data in HMTL
    We can display existing data on the variable $users in list HTML. Because $users is an array we can do foreach() to extract the data.

Example:

<?php 
    require_once 'class/Pagination.php'
    $pagination =  new Pagination('users');
    $users = $pagination->get_data();
?>
<!DOCTYPE html>
<html>
<head>
    <title>Pagination PDO Class</title>
</head>
<body>  
    <ul>
        <? foreach ($users as $user): ?>
            <li><? echo $user->username. ':' .$user->email;?> </li>
        <? endforeach; ?>
    </ul>
</body>
</html>
  • to extract data, we can make initialization with $users as $user. now we can expend the value with $user-> key. We can use : and endforeach; to replace {}.

Screenshot_7.png

  • The result
    testing.gif

We can see in the picture, the parameter query we do successfully process in the database. so when we want to open the third page. we can pass ?page=3 in the browser URL.

  • get_pagination_numbers()
    We can use this function to display the pages that can be clicked by the user. We have created this function in the class of pagination {}, here's how to use it:

Example:

<?php 
    require_once 'class/Pagination.php';
    $pagination  = new Pagination('users');
    $users = $pagination->get_data();
    $pages  = $pagination->get_pagination_numbers();
?>


  • Use data in HMTL
    The results of the get_pagination_numbers () function is the number of pages. We can do for() to sort it.

Example:

<?php 
    require_once 'class/Pagination.php'
    $pagination =  new Pagination('users');
    $users = $pagination->get_data();
    $pages  = $pagination->get_pagination_numbers();
?>
<!DOCTYPE html>
<html>
<head>
    <title>Pagination PDO Class</title>
</head>
<body>  
    <ul>
        <? foreach ($users as $user): ?>
            <li><? echo $user->username. ':' .$user->email;?> </li>
        <? endforeach; ?>
    </ul>
    <hr>
    <? for($=i; $i<=$pages; $i++): ?>
        <a href="?page=<? echo $i;?>"><? echo $i;</a>
    <? endfor; ?>
</body>
</html>
  • We do for the$pages variable that contains the number of pages.We can use : and endforeach; to replace {}.

  • The result

example3.gif

Thank you for following this tutorial, in the next section I will create a better user interface on the page number.

Proof of Work Done

https://github.com/Ryanalfarisi/paginationOOP

Sort:  

Hey alfarisi94, thank you for your contribution. Nice work with the markdowns. Looking forward for your next contribution!

Your contribution has been evaluated according to Utopian rules and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post,Click here


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Hey @alfarisi94, your contribution was unvoted because we found out that it did not follow the Utopian rules.

Upvote this comment to help Utopian grow its power and help other Open Source contributions like this one.

Want to chat? Join us on Discord.

Coin Marketplace

STEEM 0.22
TRX 0.20
JST 0.034
BTC 91793.75
ETH 3121.53
USDT 1.00
SBD 3.17