Pagination with codeigniter not working properly - php

i applied pagination but it shows whole result on one page or if i applied it with Limit
in my query then it is showing same 20 results on every page.
This is the Controller file:
public function hhh($offset = 0 )
{
$sql_query = "select username from valenth_user where banned=1 limit 0,20";
$query = $this->db->query($sql_query)->result_array();
$data["pages"]=$query;
$this->load->library("pagination");
$config = array();
$row = count($pages);
$config['base_url'] = base_url().'/test/hhh/';
$config['total_rows'] = 120;
$config['per_page'] = 20;
$config['uri_segment'] = 3;
$this->pagination->initialize($config);
//$data['pages'] = $this-db-get('valenth_user', 10, $offset);
$this-load-library("pagination");
$this-template-load('template/template','onlinee',$data);
//$data['pages'] = $this->db->get($query, 10, $offset);
$query = array_slice($query-result_array(),$rows,$config['per_page']);
}
And that is view:
<?
$rows = count($pages);
foreach($pages AS $hhh)
{
$user = new user ($hhh['username'],'username');
$hhh['username'] = $user->makeLink();
echo $hhh['username']."<br>";
}
?> <?php echo $this-pagination-create_links(); ?>

Try it like this
Model
public function get_users($limit,$offset)
{
$sql_query = "select username from valenth_user where banned=1 limit $limit,$offset";
return $this->db->query($sql_query)->result_array();
}
public function get_total_users_count()
{
$sql_query = "select username from valenth_user where banned=1 ";
$query = $this->db->query($sql_query);
return count($query->result_array());
}
Controller
public function hhh()
{
$offset = $this->uri->segment(3,0);
$limit = $this->uri->segment(4,20);
$this->mymodel->get_total_users_count();
$config['base_url'] = site_url('test/hhh');
$config['total_rows'] = $this->mymodel->get_total_users_count();
$config['per_page'] = 20;
$config['uri_segment'] = 3;
$this->load->library("pagination");
$this->pagination->initialize($config);
$data["pages"] = $this->mymodel->get_users($limit,$offset);
$data["links"] = $this->pagination->create_links();
$this->template->load('template/template','onlinee',$data);
}

Related

Select and display Single Value from SQL using PHP

consider we have a database with lots of people's details.
I want to filter that result buy available data.
if the table structure is like following,
How to display only results from user with country "India".
It will be possible by accessing object attributes, but I want to add this feature to the following script.
I am not an expert and this script seems to be so difficult for me to understand.
Pagination.php
<?php
namespace Phppot;
use Phppot\DataSource;
class Pagination
{
private $ds;
function __construct()
{
require_once __DIR__ . './../lib/DataSource.php';
$this->ds = new DataSource();
}
public function getPage()
{
// adding limits to select query
require_once __DIR__ . './../Common/Config.php';
$limit = Config::LIMIT_PER_PAGE;
// Look for a GET variable page if not found default is 1.
if (isset($_GET["page"])) {
$pn = $_GET["page"];
} else {
$pn = 1;
}
$startFrom = ($pn - 1) * $limit;
$query = 'SELECT * FROM tbl_animal LIMIT ? , ?';
$paramType = 'ii';
$paramValue = array(
$startFrom,
$limit
);
$result = $this->ds->select($query, $paramType, $paramValue);
return $result;
}
public function getAllRecords()
{
$query = 'SELECT * FROM tbl_animal';
$totalRecords = $this->ds->getRecordCount($query);
return $totalRecords;
}
}
?>
I just want to filter the result.
Full script link https://phppot.com/php/how-to-add-pagination-in-php-with-mysql/
If possible, please add an option to filter the result by an animal name (Common Name), for example "Lion".
Update, here is the working code
<?php
namespace Phppot;
use Phppot\DataSource;
class Pagination
{
private $ds;
function __construct()
{
require_once __DIR__ . './../lib/DataSource.php';
$this->ds = new DataSource();
}
public function getPage()
{
// adding limits to select query
require_once __DIR__ . './../Common/Config.php';
$limit = Config::LIMIT_PER_PAGE;
// Look for a GET variable page if not found default is 1.
if (isset($_GET["page"])) {
$pn = $_GET["page"];
} else {
$pn = 1;
}
$startFrom = ($pn - 1) * $limit;
$query = 'SELECT * FROM tbl_animal WHERE common_name=Lion LIMIT ? , ?';
$paramType = 'ii';
$paramValue = array(
$startFrom,
$limit
);
$result = $this->ds->select($query, $paramType, $paramValue);
return $result;
}
public function getAllRecords()
{
$query = 'SELECT * FROM tbl_animal WHERE common_name=Lion';
$totalRecords = $this->ds->getRecordCount($query);
return $totalRecords;
}
}
?>
Found solution
<?php
namespace Phppot;
use Phppot\DataSource;
class Pagination
{
private $ds;
function __construct()
{
require_once __DIR__ . './../lib/DataSource.php';
$this->ds = new DataSource();
}
public function getPage()
{
// adding limits to select query
require_once __DIR__ . './../Common/Config.php';
$limit = Config::LIMIT_PER_PAGE;
// Look for a GET variable page if not found default is 1.
if (isset($_GET["page"])) {
$pn = $_GET["page"];
} else {
$pn = 1;
}
$startFrom = ($pn - 1) * $limit;
$query = 'SELECT * FROM tbl_animal WHERE common_name=Lion LIMIT ? , ?';
$paramType = 'ii';
$paramValue = array(
$startFrom,
$limit
);
$result = $this->ds->select($query, $paramType, $paramValue);
return $result;
}
public function getAllRecords()
{
$query = 'SELECT * FROM tbl_animal WHERE common_name=Lion';
$totalRecords = $this->ds->getRecordCount($query);
return $totalRecords;
}
}
?>

PHP Codeigniter Pagination

Hello i am stuck on codeigniter pagination.I am getting total rows 6, per page showing 2 row.
I am getting pagination link {Page: 1,2,3} where 1 is not clickable. On Clicking Page no:2 my link look like localhost/demo/index.php/home/press/?per_page=0/2 but i am getting error on sql
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '/2,2' at line 1
SELECT * FROM media where media_type = 'PRESS' AND id <> 0 ORDER BY id DESC LIMIT 0/2
Same Error,pagintaion link getting when i click on link : 3
I dont know how to fix this issue.I am sharing my code which i used on my controller,model and view.
My controller code:
function press()
{
$this->load->model('Home_model');
$page= $this->input->get('per_page') ? $this->input->get('per_page') : 0;
$this->load->library('Pagination');
$data['page'] = $this->input->get('page');
if($data['page'] == '') {
$data['page'] = $config['per_page'] = '2'; // Per Page
} else {
$data['page'] = $config['per_page'] = $this->input->get('page');
}
$config['first_url']='0';
$pageno = $this->input->get('per_page');
if($pageno == ''){
$pageno = '0';
}
$url_to_paging = $this->config->item('base_url');
$config['base_url'] = $url_to_paging.'home/press/?per_page='.$page;
$return = $this->Home_model->pressdata($config['per_page'],$pageno, $data);
$data['pressdata'] = $return['result']; // Get Two Row Data
$config['total_rows'] = $return['count']; // Total Count 6
$this->pagination->initialize($config);
$this->load->view('press',$data);
}
Model :
function pressdata($pg_num, $offset, $content)
{
if($offset == ''){
$offset = '0';
}
$sql = "SELECT * FROM media where media_type = 'PRESS' AND id <> 0";
if($pg_num!=0 || $pg_num!="")
{
$sql .= " ORDER BY id DESC LIMIT ".$offset.",".$pg_num;
}
$query = $this->db->query($sql);
$sql_couint = "SELECT * FROM media where media_type = 'PRESS' AND id <> 0";
$query1 = $this->db->query($sql_couint);
$ret['result'] = $query->result();
$ret['count'] = $query1->num_rows();
return $ret;
}
Try it like this
$this->load->library('pagination');
$this->load->model('Home_model');
$config['base_url'] = base_url().'home/press/;
$config['total_rows'] = 200; // Total no of rows returned from the database table
$config['uri_segment'] = 3; // It is the page no,used as offset in model
$offset = 0;
if ($this->uri->segment($config['uri_segment']) != "") {
$offset = $this->uri->segment($config['uri_segment']);
}
$config['per_page'] = 20; // you can change it as you want
$return = $this->Home_model->pressdata($config['per_page'],$offset, $data);
$this->pagination->initialize($config);
In your model you can do something like this
function pressdata($per_page, $offset) {
if($per_page !== '' && $offset !== '') {
$this->db->limit($per_page, $offset);
}
//rest of your query
}
Don't copy paste it though, I just wanted to give you an idea. Modify it, implement it according to your needs. Let me know if it worked. Go through CodeIgniter's pagination library for more detailed documentation.
Finally i found the way to solve this problem.
Here are the final code for Controller, Model, View.
Controller Code :
function press()
{
$this->load->library('pagination');
$url_to_paging = $this->config->item('base_url'); // URL here (www.example.com)
$config['base_url'] = $url_to_paging.'home/press/'; // www.example.com/home/press
$config['per_page'] = '4'; // Per Page Data Show 4
$data = array();
$return = $this->Home_model->pressdata($config['per_page'],$this->uri->segment(3));
$data['pressdata'] = $return['result'];
$config['total_rows'] = $return['count'];
$this->pagination->initialize($config);
$this->load->view('press', $data);
}
Model Code :
function pressdata($num, $offset)
{
if($offset == '')
{
$offset = '0';
}
$sql = "SELECT * FROM media where media_type = 'PRESS' AND id <> 0 ";
if($num!='' || $offset!='')
{
$sql .= " order by id desc limit ".$offset.",".$num."";
}
$query = $this->db->query($sql);
$sql_count = "SELECT * FROM media WHERE media_type = 'PRESS' AND id <> 0";
$query1 = $this->db->query($sql_count);
$ret['result'] = $query->result_array();
$ret['count'] = $query1->num_rows();
return $ret;
}
View Page for pagination link :
if($this->pagination->create_links()) { ?>
<div style="clear:both; border-top: solid 1px #e9ecf1;"></div>
<div style="float:right;">
<span class="pagination" style="margin:0px; border:none;">
<?php echo $this->pagination->create_links(); ?>
</span>
</div>
<?php }
function pressdata($pg_num, $offset, $content)
{
if($offset == ''){
$offset = '0';
}
$sql = "SELECT * FROM media where media_type = 'PRESS' AND id => 0";
if($pg_num!=0 || $pg_num!="")
{
$sql .= " ORDER BY id DESC LIMIT ".$offset.",".$pg_num;
}
$query = $this->db->query($sql);
$sql_couint = "SELECT * FROM media where media_type = 'PRESS' AND id => 0";
$query1 = $this->db->query($sql_couint);
$ret['result'] = $query->result();
$ret['count'] = $query1->num_rows();
return $ret;
}
<-------id should be greater and equal to zero----->

Out Of Memory Exception Xampp

I have this function :
public function RemplirTab($nomCol)
{
$username = $this->getDb()->getUsername();
$sql = "SELECT DISTINCT $nomCol
FROM nautilus_users_page, nautilus_users_acces, nautilus_users_droit, nautilus_users_privilege, nautilus_users_menu
WHERE nautilus_users_page.id_page = nautilus_users_acces.id_page
AND nautilus_users_acces.id_droit = nautilus_users_droit.id_droit
AND nautilus_users_droit.id_droit = nautilus_users_privilege.id_droit
AND nautilus_users_page.id_menu = nautilus_users_menu.id_menu
AND login='$username'";
$row = $this->getDb()->fetchAssoc($sql, array($nomCol, $username));
$i = -1;
$Tab = array();
while($result = $row)
{
$i = $i+1;
$Tab[$i] = $result[$nomCol];
}
return $Tab;
}
Which shows me an error:
I use Silex with Doctrine DBAL.
This function was mysqli with this form:
function RemplirTab($nomCol, $login)
{
$sql = "SELECT DISTINCT $nomCol
FROM nautilus_users_page, nautilus_users_acces, nautilus_users_droit, nautilus_users_privilege, nautilus_users_menu
WHERE nautilus_users_page.id_page = nautilus_users_acces.id_page
AND nautilus_users_acces.id_droit = nautilus_users_droit.id_droit
AND nautilus_users_droit.id_droit = nautilus_users_privilege.id_droit
AND nautilus_users_page.id_menu = nautilus_users_menu.id_menu
AND login='$login'";
$link = connectdb('nautilus_users');
$req = execquery($link, utf8_decode($sql));
$i = -1;
while($row = $req->fetch_assoc())
{
$i = $i+1;
$Tab[$i] = $row[$nomCol];
}
return $Tab;
}

PHP pagination not changing when next button is pressed

I am trying to do a simple pagination where it'll retrieve data from MySQL and show a previous and next button, no numbers for counting pages, although once the next button is pressed no information are updated, I am not sure if I should use a while or foreach loop.
query
pageClass.php
public function classname
{
$start_page = 0;
$per_page = 8;
if(!isset($_GET['page']))
{
$page = 1;
} else {
$page = $_GET['page'];
}
if($page<=1)
$start_page = 0;
else
$start_page = $page * $per_page - $per_page;
$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
$sth = $this->db->prepare("SELECT * FROM articles ORDER BY article_uid DESC LIMIT ?, ?");
$sth->execute(array($start_page, $per_page));
$row = $sth->fetchAll();
return $row;
}
then in a .php file I am displaying it this way, I get the titles but once the buttons are pressed, no other page is opened.
index.php
foreach($latestArticles as $article)
{
$title = $latest['title'];
echo '<div>'.$title.'</div>';
}
$prev = $page - 1;
$next = $page + 1;
echo "
<a href='?page=$prev'>prev</a>
<a href='?page=$next'>next</a>
";
I don't want to put div's in the php classes as it would be a pain to find each class in folders to edit. What am I doing wrong?
First i would recommend you to change your pageClass.php to something more abstract
<?PHP
class pageClass
{
private $db;
private $articlesPerPage = 8;
private $startPage = 0;
public function __construct($db)
{
#TODO check if $db is valid PDO
$this->db = $db;
}
public function setArticlesPerPage($articlesPerPage)
{
$this->articlesPerPage = $articlesPerPage;
}
public function setStartPage($startPage)
{
$this->startPage = $startPage;
}
public function getArticles()
{
$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
$query = $this->db->prepare("SELECT * FROM articles ORDER BY article_uid DESC LIMIT ?, ?");
$queryResult = $query->execute(array($this->startPage, $this->articlesPerPage));
return $queryResult;
}
}
Try to change your index.php to the following
<?PHP
$page = (int)$_GET['page'];
$pageClass = new pageClass($pdo);
if($page > 0)
{
$pageClass->setStartPage($page);
}
$lastestArticles = $pageClass->getArticles();
foreach($lastestArticles as $article)
{
echo '<div>'.$article['title'].'</div>';
}
echo 'prev';
echo 'next';
?>
NOTE: THIS IS EXAMPLE CODE. YOU SHOULD EDIT IT BEFORE COMMITING TO PRODUCTION

PHP: Reuse JQGrid response for Displaying data in DataTable

First of all I am using JQGrid in my application. After changing my CSS to Bootstrap CSS.
I have to use DataTable. I want to reuse my controller pages which makes query to display the data in JQGrid.
Here is my controller page.
<?php
require_once("JsonHeader.php");
$at = $_SESSION['abc'];
$start_date = $_SESSION['start_date'];
$end_date = $_SESSION['end_date'];
if ($_SESSION['list'] == '-1') {
$user_query = "";
} else {
$user_list = $_SESSION['list'];
$user_query = " AND a.user_id IN ($list)";
}
$start_date = $_SESSION['start_date'];
$end_date = $_SESSION['end_date'];
if ($_SESSION['list'] == '-1') {
$user_query = "";
} else {
$user_list = $_SESSION['list'];
$user_query = " AND a.user_id IN ($list)";
}
$page = $_GET['page']; // get the requested page
$limit = $_GET['rows']; // get how many rows we want to have into the grid
$sidx = $_GET['sidx']; // get index row - i.e. user click to sort
$sord = $_GET['sord']; // get the direction
$qtype = ''; // Search column
$query = ''; // Search string
if (isset($_GET['searchField'])) {
$qtype = mysql_real_escape_string($_GET['searchField']);
}
if (isset($_GET['searchString'])) {
$query = mysql_real_escape_string($_GET['searchString']);
}
if (isset($_GET['searchOper'])) {
switch ($_GET['searchOper']) {
case 'eq':
$oper = '=';
$query = mysql_real_escape_string($_GET['searchString']);
break;
case 'ne':
$oper = '!=';
$query = mysql_real_escape_string($_GET['searchString']);
break;
case 'cn':
$oper = 'like';
$query = "%".mysql_real_escape_string($_GET['searchString'])."%";
break;
}
}
$searchSql1 = ($qtype != '' && $query != '') ? "and $qtype $oper '$query'" : '';
if (!$sidx)
$sidx = 1; // connect to the database
$result = mysql_query(sprintf("SELECT ae.col1,ae.col2,ae.col3, ae.col4,ae.col5,ae.col6,ae.col7,a.col8,a.col9,r.col10,p.col11
FROM $tablename3 ae,$tableName a, $tablename1 p, $tablename2 r
WHERE ae.col1=$at $searchSql1
AND a.col1 = $at
AND a.col5=r.col5
AND a.col6=p.col6
$user_query"));
$row = mysql_num_rows($result);
$count = $row;
if ($count > 0) {
$total_pages = ceil($count / $limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages)
$page = $total_pages; $start = $limit * $page - $limit; // do not put
$limit * ($page - 1);
$SQL = sprintf("SELECT ae.col1,ae.col2,ae.col3, ae.col4,ae.col5,ae.col6,ae.col7,a.col8,a.col9,r.col10,p.col11
FROM $tablename3 ae,$tableName a, $tablename1 p, $tablename2 r
WHERE ae.col1=$at $searchSql1
AND a.col1 = $at
AND a.col5=r.col5
AND a.col6=p.col6
$query");
$result = mysql_query($SQL) or die("Couldn t execute query." . mysql_error());
$responce = new stdClass();
$responce->page = new stdClass();
$responce->total = new stdClass();
$responce->records = new stdClass();
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
$i = 0;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$responce->rows[$i]['id'] = $row['col1'];
$responce->rows[$i]['cell'] = array($row['col1'], $row['col2'], $row['col3'], $row['col4'], $row['col5'], $row['col6'], $time, $row['col7']);
$i++;
}
echo json_encode($responce);
?>
HOW can I change this for DataTable?.
Please provide me the best way...
Finally I found how to resue my controller page for DataTable. Simply change the post variables in the controller page.
Like
$_GET['page']; By $_REQUEST['sEcho']
$_GET['rows']; By $_REQUEST['iDisplayStart'],$_REQUEST['iDisplayLength']
$_GET['sord']; $_REQUEST['sSortDir_0']
$_GET['searchString']: $_GET['sSearch']:
And some changes the json response like
$ans['iTotalRecords'] = $count;
$ans['iTotalDisplayRecords'] = $count;
$ans['aaData'] = $aadata;
echo json_encode($ans);

Categories