Thursday, November 22, 2007

Paging in CodeIgniter PHP

Paging in CodeIgniter PHP


CONTROLLER

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class City extends CI_Controller {
    public function __construct() {
        parent:: __construct();
        $this->load->helper("url");
        $this->load->model("Cities");
        $this->load->library("pagination");
    }
    public function index() {
        $this->load->view('welcome_message');
    }
    public function page() {
        $config = array();
        $config["base_url"] = base_url() . "city/page";
        $config["total_rows"] = $this->Cities->city_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->Cities->fetch_cities($config["per_page"], $page);
        $data["links"] = $this->pagination->create_links();
        $this->load->view("city_view", $data);
    }
}


MODEL

<?php class Cities extends CI_Model {
    public function __construct() {
        parent::__construct();
        $this->load->library('pagination');
        $this->load->database();
    }
    public function city_record_count() {
        $this->db->where('city_id >', 10);
        $this->db->from('cities');
        return $this->db->count_all_results();
        //return $this->db->count_all("cities");
    }

    public function fetch_cities($limit, $start) {
        $this->db->limit($limit, $start);
        $this->db->where('city_id >', 10);
        $this->db->order_by("city_name", "asc");
        $query = $this->db->get("cities");
        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $data[] = $row;
            }
            return $data;
        }
        return false;
   }
}



VIEW

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Welcome to CodeIgniter</title>
</head>
<body>
 <div id="container">
  <h1>Cities</h1>
  <div id="body">
<?php
foreach($results as $data) {
    echo $data->city_id . " - " . $data->city_name . "<br>";
}
?>
   <p><?php echo $links; ?></p>
  </div>
  <p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds</p>
 </div>
</body>
</html>

No comments:

Post a Comment