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.
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);
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 Name | Argument Type | Description | Examples |
|---|---|---|---|
| $from | string | The SQL FROM clause | 'users' |
| $fields | string|array | The fields to select | 'id, username, email' |
| $where | ?array | An array of SQL WHERE conditions | ['status' => 'active'] |
| $parameters | ?array | An array with the followings optional key/value pairs:[ | ['limit' => 10] |
| $debug | bool|string | The Debug mode | false, true or 'silent' |
$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);
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.
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.