Pagination - Select and Paginate Results

Selecting and Paginating Results in PowerLite PDO - Step-by-step guide on how to use PowerLite PDO for efficient record selection and pagination.

This guide provides a step-by-step tutorial on how to use PowerLite PDO for efficient record selection and pagination. We will be using the Pagination class from the PowerLite PDO library.

Step 1:Loading the Pagination class

To use the Pagination class, you first need to load it within the Dependency Injection (DI) container.

use Migliori\PowerLitePdo\Pagination;

$container = require_once __DIR__ . '/../src/bootstrap.php';
$pagination = $container->get(Pagination::class);

Step 2: Selecting Records

The Pagination class provides a select method to fetch data from the database.

public function select(
    string $from,
    $fields,
    $where = [],
    array $parameters = [],
    $debug = false
): self
Argument NameArgument TypeDescriptionExamples
$fromstringThe SQL FROM clause
'users'
'users INNER JOIN profiles ON users.id = profiles.user_id'
$fieldsstring|arrayThe fields to select
'id, username, email'
['id', 'username', 'email']
$where?arrayAn array of SQL WHERE conditions
['status' => 'active']
['users.id' => 'profiles.user_id']
['users.id >' => 10]
['users.id >' => 10, 'users.username LIKE' => '%me%']
$parameters?arrayAn array with the followings optional key/value pairs:
[
'selectDistinct' => bool,
'orderBy' => string,
'groupBy' => string,
'limit' => int|string
]
['limit' => 10]
['orderBy' => 'username ASC']
$debugbool|stringThe Debug modefalse, true or 'silent'

Examples

$from = 'users'; // The SELECT FROM clause
$fields = ['id', 'name', 'email']; // The columns you want to select
$where = ['status' => 'active']; // The conditions for the WHERE clause
$parameters = ['orderBy' => 'name'];
$pagination->select($from, $fields, $where, $parameters);

Step 3: Fetching and Displaying Records

After selecting the records, you can fetch and display them using a while loop:

$records = [];
while ($record = $pagination->fetch()) {
    $records[] = $record->id . ', ' . $record->username . ', ' . $record->email;
}
echo implode('<br>', $records);

This code fetches each record and adds it to the $records array. The records are then displayed as a string, with each record separated by a line break.

Step 4: Paginating Results

The Pagination class also provides a pagine method to generate pagination links. Here's how to use it:

$url = '/examples/pagination-examples.php'; // The URL for the pagination links
echo $pagination->pagine($url);

This code generates pagination links for the URL /examples/pagination-examples.php.

For more advanced usage, such as setting the number of records per page or customizing the pagination links, refer to the next page about Pagination Options.

Please note that this guide provides a basic overview of how to use the Pagination class. For more detailed examples, refer to the examples/pagination-examples.php file.