PHP Codeigniter Pagination - php

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----->

Related

PHP dynamic previous/next links

I have a table called "product".
I'm displaying all the data from PHP product view page by using the id parameter.
With my code:
if(isset($_GET['id'])) {
$id = $_GET['id'];
}
$query = "SELECT * FROM product WHERE id = $id ";
$select_product = $db->query($query);
while($row = $db->fetch_object($select_product)) {
$status = $row->status;
if($status == 'published') {
$title = $row->title;
echo $title;
}
}
I can pull all the data I need. In this example I can echo the title.
But how do I display a dynamic next page link? That goes same for previous link.
When I try with this code:
$query = "SELECT id FROM product";
$select_ids = $db->query($query);
while($row = $db->fetch_object($select_ids)) {
$ids = $row->id;
echo $ids;
}
I can see all the pages from that table. In my case they are 20,21,22...28
Next, I've tried like this:
$query = "SELECT id from product";
$select_ids = $db->query($query);
if($select_ids->num_rows > 0) {
$next = $id + 1;
echo 'Next';
} else {
}
With this code, my "next" link successfully goes to the next page. But, when it finishes with the result, in this case when I'm on page 28, the next dynamic link goes to empty page (29). Also this is not a good approach, because if some page, let's say 25 is deleted, the next link won't skip that page.
How can I improve that dynamic "next" link?
So first of all, you need two queries one for getting the data to display and another for counting the number of rows, also we'll need some additional variables.
Here comes the code:
$page = 1;
if(isset($_GET['page'])) {
$page = $_GET['page'];
}
$numberOfResultsPerPage = 10;
$offset = $numberOfResultsPerPage * ($page - 1)
$count = $db->query("SELECT COUNT(id) as num FROM product");
while($row = $db->fetch_object($count)) {
$numberOfRows = $row->num;
}
$query = "SELECT id FROM product LIMIT ". $offset.", ".$numberOfResultsPerPage;
$select_ids = $db->query($query);
while($row = $db->fetch_object($select_ids)) {
$ids = $row->id;
echo $ids;
}
if($page > 1) {
echo 'Prev';
}
if($page < ceil($numberOfRows / $numberOfResultsPerPage)) {
echo 'Next';
}
UPDATE:
In case you need to just find the next and previous product of the product this is the solution. It is not good if you'll have lots of products but in case the number of products is under 1000 there should not be any problems:
if(isset($_GET['id'])) {
$id = $_GET['id'];
}
$query = "SELECT id from product";
$select_ids = $db->query($query);
$ids = array();
$i = 0;
while($row = $db->fetch_object($select_ids)) {
$ids[$i] = $row->id;
if($row->id == $id) {
$index = $i;
}
$i++;
}
if(isset($ids[$index-1])) {
echo 'Prev';
}
if(isset($ids[$index+1])) {
echo 'Next';
}

PHP Change Function Query to be Direct Query Without Call The Function

I have an PHP code function get_news().
get_news function
function get_news(){
if($result = $this->db->query('SELECT * FROM tb_post WHERE post_id<>1 ORDER BY post_date DESC LIMIT 50')){
$return = '';
while($r = $result->fetch_object()){
$return .= '<p>id: '.$r->post_id.' | '.htmlspecialchars($r->post).'</p>';
}
return $return;
}
}
Now, I have 1 php file for fetching the data
if(isset($_POST) && !empty($_POST['counter']) && (int)$_POST['counter']!=$data['current']){
//the counters are diffrent so get new message list
$data['news'] = '';
$data['news'] .= $db->get_news();
$data['update'] = true;
}
My question is, how can I change the $db->get_news(); to be a direct query without call the function?
Try this
$news = '';
if($result = $this->db->query('SELECT * FROM tb_post WHERE post_id<>1 ORDER BY post_date DESC LIMIT 50')){
$return = '';
while($r = $result->fetch_object()){
$news .= '<p>id: '.$r->post_id.' | '.htmlspecialchars($r->post).'</p>';
}
}
$data['news'] = $news;
$data['update'] = true;

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

Pagination with codeigniter not working properly

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);
}

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