Php Pagination class and display issue - php

I have a php pagination class with code as follows:
<?php
class Pagination {
private $num_pages = 1;
private $start = 0;
private $display;
private $start_display;
function __construct ($query, $display=10) {
if (!empty($query)) {
$this->display = $display;
if (isset($_GET['display']) && is_numeric($_GET['display'])) $this->display = (int) $_GET['display'];
if (isset($_GET['np']) && is_numeric($_GET['np']) && $_GET['np'] > 0) {
$this->num_pages = (int) $_GET['np'];
} else {
if (is_numeric($query)) {
$num_records = $query;
} else {
$result = db_query ($query);
if ($result->num_rows > 1 || strstr($query, 'COUNT') === false) {
$num_records = $result->num_rows;
} else {
$row = $result->fetch_row();
$num_records = $row[0];
}
}
if ($num_records > $this->display) $this->num_pages = ceil ($num_records/$this->display);
}
if (isset($_GET['s']) && is_numeric($_GET['s']) && $_GET['s'] > 0) $this->start = (int) $_GET['s'];
$this->start_display = " LIMIT {$this->start}, {$this->display}";
}
}
public function display ($split=5) {
global $page;
$html = '';
if ($this->num_pages <= 1) return $html;
//$page->link('pagination.css');
$url = $page->url ('add', '', 'np', $this->num_pages);
$current_page = ($this->start/$this->display) + 1;
$begin = $current_page - $split;
$end = $current_page + $split;
if ($begin < 1) {
$begin = 1;
$end = $split * 2;
}
if ($end > $this->num_pages) {
$end = $this->num_pages;
$begin = $end - ($split * 2);
$begin++; // add one so that we get double the split at the end
if ($begin < 1) $begin = 1;
}
if ($current_page != 1) {
$html .= '<a class="first" title="First" href="' . $page->url('add', $url, 's', 0) . '">«</a>';
$html .= '<a class="prev" title="Previous" href="' . $page->url('add', $url, 's', $this->start - $this->display) . '">Previous</a>';
} else {
$html .= '<span class="disabled first" title="First">«</span>';
$html .= '<span class="disabled prev" title="Previous">Previous</span>';
}
for ($i=$begin; $i<=$end; $i++) {
if ($i != $current_page) {
$html .= '<a title="' . $i . '" href="' . $page->url('add', $url, 's', ($this->display * ($i - 1))) . '">' . $i . '</a>';
} else {
$html .= '<span class="current">' . $i . '</span>';
}
}
if ($current_page != $this->num_pages) {
$html .= '<a class="next" title="Next" href="' . $page->url('add', $url, 's', $this->start + $this->display) . '">Next</a>';
$last = ($this->num_pages * $this->display) - $this->display;
$html .= '<a class="last" title="Last" href="' . $page->url('add', $url, 's', $last) . '">»</a>';
} else {
$html .= '<span class="disabled next" title="Next">Next</span>';
$html .= '<span class="disabled last" title="Last">»</span>';
}
return '<div class="pagination">' . $html . '</div>';
}
public function limit () {
return $this->start_display;
}
}
?>
I am calling the class as follows:
$page->link('pagination.css');
$links = new Pagination ($numrows);
I have a mysql query with LIMIT as $links->limit() and it is displaying 10 records correctly.
I am calling pagination display as:
$html .= $links->display();
But no pagination is displayed and I am getting the following error:
PHP Notice: Undefined variable: page in ......
and
Call to a member function link() on a non-object on line
$page->link('pagination.css');
I have the pagination.css file uploaded in the same folder too....
What is wrong with my code ?? Why am i getting the Notice that php is undefined variable though having a global scope in the class method? And Call to a member function link() on a non-object ??
Thanks in advance.
Note: Got the pagination Class from the following link:
Pagination Class Source

You have created an Class Definition, but never created an Instance of this Class Definition.
you have to instantiate class ?$page? in PHP to get an Instance in form of an object of it. For your example code you have to hold (save) this object instance in an variable with name "page" which was previously defined with global keyword.
$html = "";
global $page;
$page->link('pagination.css');
$links = new Pagination ($numrows);
$html .= $page->display();
var_dump($html);
HTH
Tobias

Related

Pagination in PHP with N number of elements per page

I need a little bit of help.
I have an XML file as a database. From it, I need to create a pagination with 25 elements per page with Next and Previous buttons, but with my skills I'm stuck at it.
At the moment, I've written this code, but every page it reset the ID from the database to 0, so it doesn't work.
<?php
$xml = simplexml_load_file("SITE_URL/database_gamecard.xml");
$ids = array();
$count = 0;
foreach($xml->gamecard as $id) {
$ids[] = $id;
}
//Order IDs by url names
//usort ($ids, function($a, $b) {
//$url = $id->url;
//return strcmp($a[$url], $b[$url]);
//});
function PopulatePage($id) {
$url = $id->url;
$img = $id->img;
echo '<a class="darken" href="' . $url . '"><img width="320" height="240" src="' . $img . '"></a>';
}
function StopCount() {
$page = intval($_GET['page']);
$pageurl = "SITE_URL/list.php?page=";
$count = 0;
$page = $page + 1;
$newurl = $pageurl . $page;
echo "<a href='" . $newurl . "'>Next</a>";
}
//Test generating pages
foreach ($ids as $id) {
$count++;
if($page == 1) {
PopulatePage($id);
if($count == 25) {
StopCount();
break;
}
}
if($page == 2) {
PopulatePage($id);
if($count == 25) {
StopCount();
break;
}
}
}
?>

for loop not working correctly with json encode Php

I am trying to fetch members ratings from the database using ajax. I passed a function to the JSON, even though it returned a value in the function but it doesn't execute the for loop condition.
Here is my code, the loop failed to execute. What am I doing wrong?
function mrate($irate) {
$class = "fa-star star-filled";
for ($i = 0; $i < 5; $i++) {
if ($irate <= $i) {
$class = "fa-star-o empty";
}
return '<i class="fa ' . $class . '"></i>';
}
}
$perPage = 2;
if (isset($_GET["page"]) && isset($_GET["page"])) {
$page = $_GET["page"];
$pid = $mysqli->real_string_escape($_GET["pid"]);
} else {
$page = 1;
$pid = $mysqli->real_string_escape($_SESSION['pid']);
};
$startFrom = ($page - 1) * $perPage;
$sqlQuery = "SELECT id, name,
review, rating, added_date
FROM review_rating
where product_id = '$pid'
ORDER BY id ASC LIMIT $startFrom, $perPage";
$result = mysqli_query($mysqli, $sqlQuery);
$paginationHtml = '';
while ($row = mysqli_fetch_assoc($result)) {
$img = '<img class="rounded-circle" width="50" src="' . $set['installUrl'] . 'assets/img/login.png" alt="' . $row["name"] . '"/>';
$irate = $row['rating'];
$paginationHtml .= '<div class="product-review pb-4 mb-4 border-bottom">';
$paginationHtml .= '<div class="d-flex mb-3">';
$paginationHtml .= '<div class="media media-ie-fix align-items-center mr-4 pr-2">' . $img;
$paginationHtml .= '<div class="media-body pl-3"><h6 class="font-size-sm mb-0">' . $row["name"] . '</h6>';
$paginationHtml .= '<span class="font-size-ms text-muted">' . $row['added_date'] . '</span></div></div>';
$paginationHtml .= '<div><div class="star-rating">' . mrate($irate) . '</div></div>';
$paginationHtml .= '</div>';
$paginationHtml .= '<p class="font-size-md mb-2">' . $row['review'] . '</p>';
$paginationHtml .= '</div>';
}
$jsonData = array(
"html" => $paginationHtml,
);
echo json_encode($jsonData);
Replace your function mrate($irate) with this and try. You needed to concatenate the stars code to display it more than once.
function mrate($irate){
$stars = '';
for($i=0; $i<5; $i++){
if($irate <= $i){
$class = "fa-star-o empty";
}else{
$class = "fa-star star-filled";
}
$stars .= '<i class="fa '.$class.'"></i>';
}
return $stars;
}
Assuming there's no fractional rating, you can do the following - Display all 5 stars but solid ones will represent the rating.
function mrate($irate){
$class = '';
for($i = 0; $i < 5; $i++){
if ($irate <= $i) {
$class .= '<i class="fa fa-star"></i>';
} else {
$class .= '<i class="fa fa-star-o"></i>';
}
}
return $class;
}

Sending user data to database without Prepared statment

I am using the pagination class below with PDO OOP
<?php
class Paginator{
private $db;
public $page_no;//current page
public $limit;//record_per page
public $row_start;
public $total_rec;
public $query;
function __construct($con){
$this->db = $con;
}
//get total no of records
public function get_no_records($query){
$this->query = $query;
$stmt = $this->db->prepare($query);
$stmt->execute();
$row_num = $stmt->rowCount();
if($row_num > 0){
$this->total_rec = $row_num;
return $row_num;
}
}
public function get_data($limit,$page_no){
try {
$this->limit = $limit;
$this->page_no = $page_no;
if($this->limit == "all"){
$query = $this->query;
}
else{
$this->row_start = (($this->page_no-1) * $this->limit);
$query = $this->query . " LIMIT ". $this->row_start . "," . $this->limit;
}
$stmt = $this->db->prepare($query);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
//create an array to hold record
$results[] = $row;
}
$result = new stdClass();
$result->page_no = $this->page_no;
$result->limit = $this->limit;
$result->total_rec = $this->total_rec;
$result->data = $results;
return $result;
} catch (PDOException $e) {
echo $e->getMessage();
}
}
public function create_links($links,$list_class){
if($this->limit == 'all'){
return '';
}
$last = ceil($this->total_rec/$this->limit);
$start = (($this->page_no - $links) > 0) ? $this->page_no - $links : 1;
$end = (($this->page_no + $links) < $last) ? $this->page_no + $links : $last;
$html = '<ul class="' . $list_class . '">';
$class = ($this->page_no == 1) ? "disabled" : "";
$previous_page = ($this->page_no == 1) ?
'<li class="' . $class . '">«</li>' :
'<li class="' . $class . '">«</li>';
$html .= $previous_page;
if($start > 1){
$html .= '<li>1</li>';
$html .= '<li class="disabled"><span>....</span></li>';
}
for($i = $start;$i<=$end;$i++){
$class = ($this->page_no == $i)? "active" : "";
$html .= '<li class="' . $class . '">' . $i . '</li>';
}
if( $end < $last){
$html .= '<li class="disabled"><span>....</span></li>';
$html .= '<li>' . $last . '</li>';
}
$class = ($this->page_no == $last)? "disabled" : "";
$next_page = ( $this->page_no == $last)?
'<li class="' . $class . '">»</li>':
'<li class="' . $class . '">»</li>';
$html .= $next_page;
$html .= '</ul>';
return $html;
}
}
?>
From the get_no_records($query) above any query passed is executed,I had a query like SELECT * FROM users and it worked fine. I have a function where the value of the column name is determined by the user input from a text field in a form
here is the function
public function search_user($value){
$query = "SELECT * FROM users WHERE username = " . "'" . $value . "'";
return $query;
}
Here is my search form
<form method="GET">
Username:<input type="text" name="uname"/>
<button type="submit" class="btn btn-primary" name="srch">Search</button>
</form>
The $query returned is passed to get_no_records($query) And it is working Fine.Here is My question. Is it right to send user input to the database that way? Is my code vulnerable to sql injection? How do i prevent this. Thanks.
You really need to use PDO prepared statements, as it is a reliable way to ensure that your website is safe from SQL Injection.
Reference: https://stackoverflow.com/a/3716402/5287820

CMB2 Filelist type paginate results (uses get_post_meta)

This is getting close to what I need. It splits out 5 results from the $files (get_post_meta) and creates pages but the images are all the same images on all the pages. I am beyond the limit of my brain.
function gallery_loop() {
if( get_query_var('page') ) {
$page = get_query_var( 'page' );
} else {
$page = 1;
}
$img_size = 'portfolio-catalog';
$files = get_post_meta(get_the_ID(), '_cmb_gallery_images', true);
$limit = 5;
$total = count( $files );
$pages = ceil( $total / $limit );
$curr_page = isset($_GET['page']);
$offset = ($curr_page - 1) * $limit;
$items_array = array_chunk((array) $files, $limit, true);
$files_array = array_slice($items_array, $offset, true); // this is showing the same 5 items on all the pages
foreach ($files_array as $files) {
echo '<div style="border:1px solid red;">'; //BEGIN "page" so I can see if they are splitting correctly
foreach ($files as $attachment_id => $attachment_url) {
$page=1;
echo '<div class="file-list-image">';
echo wp_get_attachment_image($attachment_id, $img_size);
echo '</div>';
$page++;
} // end $files as $attachment_id => $attachment_url
echo '</div>'; //END "page" so I can see if they are splitting correctly
} // end foreach $files_array as $files
//the correct amount of pages are showing up but the items are all the same
echo paginate_links( array(
'base' => get_permalink() . '%#%' . '/',
'format' => '?page=%#%',
'current' => $page,
'total' => $pages
) );
}
// end function
Something like this should do the trick.
PHP
<?php
$files_array=array_chunk((array) $files, 10, true); //10 is an amount per page here
foreach ($files_array as $files)
{
$page=1;
echo '<div data-imgpage="' . $page . '" class="images_page' . (($page > 1) ? 'hidden_class' : '') . '">';
foreach ($files as $attachment_id => $attachment_url)
{
echo '<div class="file-list-image">';
echo wp_get_attachment_image($attachment_id, $img_size);
echo '</div>';
}
echo '</div>';
$page++;
}
// now create some pagination if needed
echo ((count($files_array) > 1) ? '<div class="pagination_container">' . create_pagination(1, count($files_array)) . '</div>' : '');
function create_pagination($current_page, $limit)
{
$first=((($current_page - 2) > 0) ? $current_page - 2 : 1);
$last=((($current_page + 2) < $limit) ? $current_page + 2 : $limit);
$html='<ul data-imglisting-pagination-max="' . $limit . '">';
if ($first > 1)
{
$html .= '<li data-imglisting-pagination-page="1" data-imglisting-pagination-action="active"><span class="page_class">1</span></li>';
$html .= '<li data-imglisting-pagination-action="disabled" class="disabled_page_class"><span>...</span></li>';
}
for ($i=$first; $i <= $last; $i ++)
{
$html .= '<li data-imglisting-pagination-page="' . $i . '" data-imglisting-pagination-action="active" ' . (($current_page == $i) ? 'class="active_page_class"' : "" ) . '><span class="page_class">' . $i . '</span></li>';
}
if ($last < $limit)
{
$html .= '<li data-imglisting-pagination-action="disabled" class="disabled_page_class"><span>...</span></li>';
$html .= '<li data-imglisting-pagination-page="' . $limit . '" data-imglisting-pagination-action="active"><span class="page_class">' . $limit . '</span></li>';
}
$html .= '</ul>';
return $html;
}
JS
jQuery(document).ready(function ($)
{
var current_page = 1;
bind_stuff();
function bind_stuff()
{
$('[data-imglisting-pagination-action="active"]').unbind('click');
$('[data-imglisting-pagination-action="active"]').click(function ()
{
if (current_page != $(this).attr('data-imglisting-pagination-page'))
{
current_page = $(this).attr('data-imglisting-pagination-page');
$('[data-imglisting-pagination-action="active"]').removeClass('active_page_class');
$('[data-imgpage]').hide();
$('[data-imgpage="' + current_page + '"]').show();
$(this).addClass('active_page_class');
$('.pagination_container').html(build_pagination(current_page, parseInt($('data-imglisting-pagination-max').attr('data-imglisting-pagination-max'))));
bindStuff();
}
});
}
});
function build_pagination(current, limit)
{
var first = (((current - 2) > 0) ? current - 2 : 1);
var last = (((current + 2) < limit) ? current + 2 : limit);
output = '<ul data-imglisting-pagination-max="' + limit + '">';
if (first > 1)
{
output = output + '<li data-imglisting-pagination-page="1" data-imglisting-pagination-action="active"><span class="page_class">1</span></li>';
output = output + '<li data-imglisting-pagination-action="disabled" class="disabled_page_class"><span>...</span></li>';
}
for (i = first; i <= last; i++)
{
output = output + '<li data-imglisting-pagination-page="' + i + '" data-imglisting-pagination-action="active" ' + ((current == i) ? 'class="active_page_class"' : "") + '><span class="page_class">' + i + '</span></li>';
}
if (last < limit)
{
output = output + '<li data-imglisting-pagination-action="disabled" class="disabled_page_class"><span>...</span></li>';
output = output + '<li data-imglisting-pagination-page="' + limit + '" data-imglisting-pagination-action="active"><span class="page_class">' + limit + '</span></li>';
}
output = output + '</ul>';
return output;
}

Custom table sorting not working correct

I am creating a data table that has sortable links but when I click on the link say "username" if i click on that multiple times it makes the url have lots of asc example: http://localhost/riwakawebsitedesigns-website/admin/users/status/ascascascascascascasc it should just be
Sorting Asc http://localhost/riwakawebsitedesigns-website/admin/users/status/asc
And then if click again and so on.
Sorting Desc http://localhost/riwakawebsitedesigns-website/admin/users/status/desc
This here is how pagination looks in url http://localhost/riwakawebsitedesigns-website/admin/users/1
I cannot figure out why each time i click on table head link that it creates so many asc etc. How can I fix it.
What's wrong with sort code. The pagination works fine. Please note I have use codeigniter pagination but not to my liking.
<?php
class Users extends MX_Controller {
public function index() {
$this->getList();
}
public function getList() {
$this->load->library('paginations');
$sort_segment = $this->uri->segment(3);
if (isset($sort_segment)) {
$sort = $sort_segment;
} else {
$sort = 'username';
}
$order_segment = $this->uri->segment(3);
if (isset($order_segment)) {
$order = $order_segment;
} else {
$order = 'asc';
}
$page_segment = $this->uri->segment(4);
if (isset($page_segment)) {
$page = $page_segment;
} else {
$page = 1;
}
$url = '';
if (isset($sort_segment)) {
$url .= $sort_segment;
}
if (isset($order_segment)) {
$url .= $order_segment;
}
if (isset($page_segment)) {
$url .= $page_segment;
}
$data['title'] = "Users";
$this->load->model('admin/user/model_user');
$admin_limit = "1";
$filter_data = array(
'sort' => $sort,
'order' => $order,
'start' => ($page - 1) * $admin_limit,
'limit' => $admin_limit
);
$user_total = $this->model_user->getTotalUsers();
$results = $this->model_user->getUsers($filter_data);
foreach ($results as $result) {
$data['users'][] = array(
'user_id' => $result['user_id'],
'username' => $result['username'],
'date_added' => $result['date_added'],
'edit' => site_url('admin/users/edit' .'/'. $result['user_id'])
);
}
$url = '';
if ($order == 'asc') {
$url .= 'desc';
} else {
$url .= 'asc';
}
if (isset($page_segment)) {
$url .= $page_segment;
}
$data['sort_username'] = site_url('admin/users' .'/'. 'username' .'/'. $url);
$data['sort_status'] = site_url('admin/users' .'/'. 'status' .'/'. $url);
$data['sort_date_added'] = site_url('admin/users' .'/'. 'date_added' .'/'. $url);
$url = '';
if (isset($sort_segment)) {
$url .= $sort_segment;
}
if (isset($order_segment)) {
$url .= $order_segment;
}
$paginations = new Paginations();
$paginations->total = $user_total;
$paginations->page = $page;
$paginations->limit = "1";
$paginations->url = site_url('admin/users' .'/'. $url .'/'. '{page}');
$data['pagination'] = $paginations->render();
$paginations_lang = "Showing %d to %d of %d (%d Pages)";
$data['results'] = sprintf($paginations_lang, ($user_total) ? (($page - 1) * $admin_limit) + 1 : 0, ((($page - 1) * $admin_limit) > ($user_total - $admin_limit)) ? $user_total : ((($page - 1) * $admin_limit) + $admin_limit), $user_total, ceil($user_total / $admin_limit));
$data['sort'] = $sort;
$data['order'] = $order;
$this->load->view('template/user/users_list.tpl', $data);
}
}
My Library
<?php
class Paginations {
public $total = 0;
public $page = 1;
public $limit = 20;
public $num_links = 8;
public $url = '';
public $text_first = '|<';
public $text_last = '>|';
public $text_next = '>';
public $text_prev = '<';
public function render() {
$total = $this->total;
if ($this->page < 1) {
$page = 1;
} else {
$page = $this->page;
}
if (!(int)$this->limit) {
$limit = 10;
} else {
$limit = $this->limit;
}
$num_links = $this->num_links;
$num_pages = ceil($total / $limit);
$this->url = str_replace('%7Bpage%7D', '{page}', $this->url);
$output = '<ul class="pagination">';
if ($page > 1) {
$output .= '<li>' . $this->text_first . '</li>';
$output .= '<li>' . $this->text_prev . '</li>';
}
if ($num_pages > 1) {
if ($num_pages <= $num_links) {
$start = 1;
$end = $num_pages;
} else {
$start = $page - floor($num_links / 2);
$end = $page + floor($num_links / 2);
if ($start < 1) {
$end += abs($start) + 1;
$start = 1;
}
if ($end > $num_pages) {
$start -= ($end - $num_pages);
$end = $num_pages;
}
}
for ($i = $start; $i <= $end; $i++) {
if ($page == $i) {
$output .= '<li class="active"><span>' . $i . '</span></li>';
} else {
$output .= '<li>' . $i . '</li>';
}
}
}
if ($page < $num_pages) {
$output .= '<li>' . $this->text_next . '</li>';
$output .= '<li>' . $this->text_last . '</li>';
}
$output .= '</ul>';
if ($num_pages > 1) {
return $output;
} else {
return '';
}
}
}
Thanks so much to #AdrienXL which gave me the idea what problem was.
I now have fixed it. I had doubled up on my page and sort and orders $_GET. So there for i have now just used uri segments and removed the doubled up code and change a couple of things in model
For people who do not want to use codeigniter pagination class.
You can use my example:
My Users:
<?php
class Users extends MX_Controller {
public function index() {
$this->load->library('paginations');
$this->load->model('admin/user/model_user');
// Sort
if (null !==($this->uri->segment(3))) {
$sort = $this->uri->segment(3);
} else {
$sort = 'username';
}
// Order
if (null !==($this->uri->segment(4))) {
$order = $this->uri->segment(4);
} else {
$order = 'asc';
}
// Page
if (null !==($this->uri->segment(3))) {
$page = $this->uri->segment(3);
} else {
$page = 1;
}
$url = '';
// Sort
if (null !==($this->uri->segment(3))) {
$url .= $this->uri->segment(3);
}
// Order
if (null !==($this->uri->segment(4))) {
$url .= $this->uri->segment(4);
}
// Page Number
if (null !==($this->uri->segment(3))) {
$url .= $this->uri->segment(3);
}
$admin_limit = "1";
$filter_data = array(
'sort' => $sort,
'order' => $order,
'start' => ($page - 1) * $admin_limit,
'limit' => $admin_limit
);
$user_total = $this->model_user->getTotalUsers();
$results = $this->model_user->getUsers($filter_data);
foreach ($results as $result) {
$data['users'][] = array(
'user_id' => $result['user_id'],
'username' => $result['username'],
'status' => ($result['status'] ? "Enabled" : "Disabled"),
'date_added' => date(strtotime($result['date_added'])),
'edit' => site_url('admin/users/edit' .'/'. $result['user_id'] . $url)
);
}
$url = '';
if ($order == 'asc') {
$url .= 'desc';
} else {
$url .= 'asc';
}
$data['sort_username'] = site_url('admin/users' .'/'. 'username' .'/'. $url);
$data['sort_status'] = site_url('admin/users' .'/'. 'status' .'/'. $url);
$data['sort_date_added'] = site_url('admin/users' .'/'. 'date_added' .'/'. $url);
$url = '';
$paginations = new Paginations();
$paginations->total = $user_total;
$paginations->page = $page;
$paginations->limit = $admin_limit;
$paginations->url = site_url('admin/users' .'/'. $url . '{page}');
$data['pagination'] = $paginations->render();
$paginations_lang = "Showing %d to %d of %d (%d Pages)";
$data['results'] = sprintf($paginations_lang, ($user_total) ? (($page - 1) * $admin_limit) + 1 : 0, ((($page - 1) * $admin_limit) > ($user_total - $admin_limit)) ? $user_total : ((($page - 1) * $admin_limit) + $admin_limit), $user_total, ceil($user_total / $admin_limit));
$data['sort'] = $sort;
$data['order'] = $order;
$this->load->view('template/user/users_list.tpl', $data);
}
}
My View
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<td class="text-left"><?php if ($sort == 'username') { ?>
Username
<?php } else { ?>
Username
<?php } ?></td>
<td class="text-left"><?php if ($sort == 'status') { ?>
Status
<?php } else { ?>
Status
<?php } ?></td>
<td class="text-left"><?php if ($sort == 'date_added') { ?>
Date Added
<?php } else { ?>
Date Added
<?php } ?></td>
<td class="text-right">Action</td>
</tr>
</thead>
<tbody>
<?php foreach ($users as $user) { ?>
<tr>
<td><?php echo $user['username'];?></td>
<td><?php echo $user['status'];?></td>
<td><?php echo $user['date_added'];?></td>
<td><a href="<?php echo $user['edit'];?>">Edit</td>
</tr>
<?php } ?>
</tbody>
</table>
<div class="row">
<div class="col-sm-6 text-left"><?php echo $pagination; ?></div>
<div class="col-sm-6 text-right"><?php echo $results; ?></div>
</div>
</div>
Model Function
public function getUsers($data = array()) {
$sql = "SELECT * FROM `" . $this->db->dbprefix . "user`";
$sort_data = array(
'username',
'status',
'date_added'
);
if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
$sql .= " ORDER BY " . $data['sort'];
} else {
$sql .= " ORDER BY username";
}
if (isset($data['order']) && ($data['order'] == 'desc')) {
$sql .= " desc";
} else {
$sql .= " asc";
}
if (isset($data['start']) || isset($data['limit'])) {
if ($data['start'] < 0) {
$data['start'] = 0;
}
if ($data['limit'] < 1) {
$data['limit'] = 20;
}
$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
}
$query = $this->db->query($sql);
return $query->result_array();
}
Routes:
$route['admin/users'] = "admin/user/users/index";
$route['admin/users/edit/(:any)'] = "admin/user/users/edit/$1";
$route['admin/users/(:any)'] = "admin/user/users/index/$1";
$route['admin/users/(:any)/(:any)/(:any)'] = "admin/user/users/index/$1/$2/$3";
Custom Library
<?php
class Paginations {
public $total = 0;
public $page = 1;
public $limit = 20;
public $num_links = 8;
public $url = '';
public $text_first = '|<';
public $text_last = '>|';
public $text_next = '>';
public $text_prev = '<';
public function render() {
$total = $this->total;
if ($this->page < 1) {
$page = 1;
} else {
$page = $this->page;
}
if (!(int)$this->limit) {
$limit = 10;
} else {
$limit = $this->limit;
}
$num_links = $this->num_links;
$num_pages = ceil($total / $limit);
$this->url = str_replace('%7Bpage%7D', '{page}', $this->url);
$output = '<ul class="pagination">';
if ($page > 1) {
$output .= '<li>' . $this->text_first . '</li>';
$output .= '<li>' . $this->text_prev . '</li>';
}
if ($num_pages > 1) {
if ($num_pages <= $num_links) {
$start = 1;
$end = $num_pages;
} else {
$start = $page - floor($num_links / 2);
$end = $page + floor($num_links / 2);
if ($start < 1) {
$end += abs($start) + 1;
$start = 1;
}
if ($end > $num_pages) {
$start -= ($end - $num_pages);
$end = $num_pages;
}
}
for ($i = $start; $i <= $end; $i++) {
if ($page == $i) {
$output .= '<li class="active"><span>' . $i . '</span></li>';
} else {
$output .= '<li>' . $i . '</li>';
}
}
}
if ($page < $num_pages) {
$output .= '<li>' . $this->text_next . '</li>';
$output .= '<li>' . $this->text_last . '</li>';
}
$output .= '</ul>';
if ($num_pages > 1) {
return $output;
} else {
return '';
}
}
}

Categories