In this tutorial, I’ll use CodeIgniter’s pagination library to show you how you can create a paginated list of results from a MySQL database.
The Model
models/countries.php
record_count() method returns the number of records and is needed because one of the options in the $config array for the pagination library is $config["total_rows"].
fetch_countries() method retrieves a list of all the records from the Country table. There are two arguments for this method: $limit and $start.
<?php
class Countries extends CI_Model
{
public function __construct() {
parent::__construct();
}
public function record_count() {
return $this->db->count_all("Country");
}
public function fetch_countries($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db->get("Country");
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
}
The Controllercontrollers/welcome.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function __construct() {
parent:: __construct();
$this->load->helper("url");
$this->load->model("Countries");
$this->load->library("pagination");
$this->load->library('table');
}
public function example1() {
$config = array();
$config["base_url"] = base_url() . "welcome/example1";
$config["total_rows"] = $this->Countries->record_count();
$config["per_page"] = 20;
$config["uri_segment"] = 3;
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data["results"] = $this->Countries->
fetch_countries($config["per_page"], $page);
$data["links"] = $this->pagination->create_links();
$this->load->view("countries_view", $data);
}
public function index()
{
$this->load->view('welcome_message');
}
}
The View
views/countries_view.php
<body>
<div id="container">
<h1>Countries</h1>
<div id="body">
<?php
foreach($results as $data) {
echo $data->printable_name . " - " . $data->iso3 . "<br>";
}
?>
<p><?php echo $links; ?></p>
</div>
<p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds</p>
</div>
</body>
URL: http://yourdomain/welcome/example1
