How to use parameter in function with pagination CodeIgniter? - php

I have function which takes state name as a parameter and displays all the cities of that specific state. Since list of cities is very long I have used pagination in the same function but when I click on the 'Next' or any other pagination link the function accepts the offset value in the $state variable. The function is
public function load_Page($state){
$this->load->database();
$this->load->library('pagination');
$a = 1;
$this->db->select("*")->where("userstate" , $a)->where("state" , $state);
$query0 = $this->db->get("city");
$this->db->select("*")->where("userstate" , $a)->where("state" , $state);
$query1 = $this->db->get('city' , 10 , $this->uri->segment(3));
$config["base_url"] = base_url()."index.php/city/load_Page";
$total_row = $query0->num_rows();
$config['page_query_string'] = TRUE;
$config["total_rows"] = $total_row;
$config["per_page"] = 10;
$this->pagination->initialize($config);
$data["state"] = $state;
$data["result"] = $query1->result();
//$data["rows"] = $query1->num_rows();
$this->load->view('header');
$this->load->view('city', $data);
$this->load->view('footer');
}
Is there any other way out to do it or I am going completely wrong?

First of all, when you are paginating, the page number has to come from the URL, and that's always available as a parameter in the controller method. It should default to page 1.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class City extends CI_Controller {
public function load_page( $state, $page = 1 ){
// I'm going to use an alias for this model
$this->load->model('example_model', 'model');
// Use the URL helper for site_url()
$this->load->helper('url');
// Set pagination config
$config['pagination_settings'] = [
'per_page' => 10,
'use_page_numbers' => TRUE,
'uri_segment' => 4, // This is very important!!!
'base_url' => site_url('city/load_page/' . $state)
];
// Get the total rows
$config['pagination_settings']["total_rows"] = $this->model->pagination_count( $state );
// Load and initialize pagination
$this->load->library('pagination');
$this->pagination->initialize($config['pagination_settings']);
$data = [
'state' => $state,
'rows' => $this->model->get_cities( $state, $page, $config['pagination_settings']['per_page'] ),
'links' => $this->pagination->create_links()
];
// Use data in views or wherever needed ...
$this->load->view('city', $data);
}
/**
* Create the rows to paginate
*/
public function setup()
{
// I'm going to use an alias for this model
$this->load->model('example_model', 'model');
$this->model->setup();
}
// -----------------------------------------------------------------------
}
Next, you should move your database queries to a model. You don't need to use transactions for your 2 select type queries.
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Example_model extends CI_Model{
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function pagination_count( $state )
{
return $this->db->where("state" , $state)
->count_all_results('city');
}
public function get_cities( $state, $page, $limit )
{
$offset = ( $page * $limit ) - $limit;
$query = $this->db->where("state" , $state)
->limit( $limit, $offset )
->get('city');
if( $query->num_rows() > 0 )
return $query->result();
return NULL;
}
/**
* Setup for testing
*/
public function setup()
{
$this->load->dbforge();
$fields = array(
'id' => array(
'type' => 'INT',
'constraint' => 5,
'unsigned' => TRUE,
'auto_increment' => TRUE
),
'state' => array(
'type' => 'VARCHAR',
'constraint' => '32',
),
'city' => array(
'type' => 'VARCHAR',
'constraint' => '32',
),
);
$this->dbforge->add_field($fields);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('city', TRUE);
for( $x = 1; $x <= 40; $x++ )
{
$this->db->insert('city', array(
'state' => 'ca',
'city' => 'x' . $x
));
}
}
}
This is the view that I used:
<?php
echo '<h1>' . $state . '</h1>';
echo $links . '<br /><br />';
foreach( $rows as $row )
{
echo $row->city . '<br />';
}
To set up the database for testing, I went to:
http://localhost/index.php/city/setup
Then to check out that the pagination works, I went to:
http://localhost/index.php/city/load_page/ca
It should work for you, as this code is now fully tested.
UPDATE --------------------
If you want to add more parameters to your pagination, do it with query strings. You will need to set the pagination config with this extra setting:
$config['pagination_settings']['reuse_query_string'] = TRUE;
That means the config would look like this:
$config['pagination_settings'] = [
'per_page' => 10,
'use_page_numbers' => TRUE,
'uri_segment' => 4, // This is very important!!!
'base_url' => site_url('city/load_page/' . $state),
'reuse_query_string' => TRUE
];
And then you create the link to the first page with your params:
http://localhost/index.php/city/load_page/ca?a=1&b=2&c=3
And because of the reuse_query_strings being set to TRUE, that means that ?a=1&b=2&c=3 would all be attached to the pagination links.

Related

How to load all rows in codeigniter-base-model? REST api

I am trying to load all rows for my REST API through Postman.
I am using codeigniter-base-model MY_Model.php.
https://github.com/jamierumbelow/codeigniter-base-model
This is how my code currently looks like both in my controller/model:
Controller(api_news.php):
class Api_News extends REST_Controller {
function __construct()
{
parent::__construct();
}
function index_get()
{
$id = $this->uri->segment(3);
$this->load->model('News_model');
$news = $this->News_model->get_by(array('id' => $id));
if(isset($news['id'])) {
$this->response(array(
'message' => 'success',
'status' => 'true',
'data' => $news));
} else {
$this->response(array(
'message' => 'unsuccess',
'status' => 'false'));
}
}
}
Model(news_model.php):
class News_model extends MY_Model{
protected $_table = 'news';
protected $primary_key = 'id';
protected $return_type = 'array';
}
At the moment if I access:
localhost/my_api/api_news/id/1, 2, 3, etc...
I can access any record by its individual ID and it shows up which is great.
BUT I also want to be able to see all rows by doing this:
localhost/my_api/api_news/id/
and have all rows showing at once.
But I am not sure how to do this...and am getting an unsuccess/false if I try.
Can you please show me how? I am new to PHP in general and I appreciate any help.
Thank you so much!!
Make some changes in your Controller function as below -
function index_get(){
$id = $this->uri->segment(3);
$this->load->model('News_model');
// pass $id to model
$news = $this->News_model->get_by( $id );
if( !empty( $news ) ) {
$this->response(array(
'message' => 'success',
'status' => 'true',
'data' => $news));
} else {
$this->response(array(
'message' => 'unsuccess',
'status' => 'false'));
}
}
And in your model make id parameter optional and then check that if id is passed get data based on id otherwise return all data as below -
// $id variable is optional here
function get_by( $id = '' ) {
if ( $id == '' ) {
$news = $this->db->get( 'news' );
}
else {
$news = $this->db->get_where( 'news', array( 'id' => $id ) );
}
// return data to controller
return $news->result();
}
So if you enter id in API then data will be based on that id otherwise all data will be returned.

call to undefined method CI_Input::load_query()

i am using codeigniter 3.0.4 framework. i have extended the input class named as MY_input.php. i have placed this file on inside the application/core folder. This is working fine on my localhost xampp server. But i am getting this error call to undefined method CI_Input::load_query() when i deploy my project folder on a live server. i have uploaded the files correctly and i have MY_input.php in application/core folder on the live server as well.
i am still running it successfully on my localhost but can't do so on live. i am pasting the relevant code here. Inside Login_controller i have
function displaySorted($query_id = 0,$sortBy = 'DeviceName',$sortOrder = 'asc',$offset=0)
{
$dataS = $this->session->userdata('logged_in');
if(isset($dataS))
{
$limit = 20;
$data['offset'] = $this->uri->segment(6);
$data['query_id']=$query_id;
$data['fields'] = array(
'ID' => 'ID',
'DeviceType' => 'Device Type',
'RegistrationDateTime' => 'RegistrationDateTime',
'LastUpdateDateTime' => 'LastUpdateDateTime',
'LastPushNotificationSent' => 'LastPushNotificationSent',
'DeviceName' => 'Device Name',
'Latitude' => 'Latitude',
'Longitude' => 'Longitude',
'CityName' => 'CityName',
'StateName' => 'StateName',
'CountryName' => 'CountryName',
'AppVersion' => 'AppVersion',
'iOSVersion' => 'iOSVersion',
'IPAddress' => 'IPAddress',
'TotalCities' => 'TotalCities',
'DeviceDID' => 'DeviceDID',
'DeviceToken'=> 'DeviceToken',
'DeviceLanguageID'=> 'DeviceLanguageID',
'LocationID' => 'LocationID',
'TempScale' => 'TempScale',
'IsFreezeAlertEnabled' => 'IsFreezeAlertEnabled',
'ShouldShowTempOnBadge' => 'ShouldShowTempOnBadge',
'ShowNegativeAsPositive' => 'ShowNegativeAsPositive',
'LastTempC' => 'LastTempC',
'LastTempF' => 'LastTempF',
'IsDeviceUsingProdCert' => 'IsDeviceUsingProdCert'
);
$this->input->load_query($query_id);
$query_array = array(
'DeviceName' => $this->input->get('DeviceName'),
'RegistrationDateTime' => $this->input->get('RegistrationDateTime'),
'LastUpdateDateTime' => $this->input->get('LastUpdateDateTime'),
'AppVersion' => $this->input->get('AppVersion'),
'iOSVersion' => $this->input->get('iOSVersion'),
'DeviceDID' => $this->input->get('DeviceDID'),
'DeviceToken' => $this->input->get('DeviceToken')
);
$results = $this->user_model->searchSorted($query_array,$limit, $offset, $sortBy, $sortOrder);
$data['tableInfo'] = $results['rows'];
$data['num_results'] = $results['num_rows'];
$data['DeviceName'] =$query_array['DeviceName']; $data['RegistrationDateTime']=$query_array['RegistrationDateTime'];
$data['LastUpdateDateTime']=$query_array['LastUpdateDateTime'];
$data['AppVersion']=$query_array['AppVersion'];
$data['iOSVersion']=$query_array['iOSVersion'];
$data['DeviceDID']=$query_array['DeviceDID'];
$data['DeviceToken']=$query_array['DeviceToken'];
//pagination functionality
$config['base_url'] = site_url("login_controller/displaySorted/$query_id/$sortBy/$sortOrder");
$config['per_page'] = $limit;
$config['total_rows'] = $data['num_results'];
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
$data['sortBy'] = $sortBy;
$data['sortOrder'] = $sortOrder;
$this->load->view('adminPanel_view', $data);
}
else
{
//echo $this->;exit;
redirect('login_controller');
}
}
Now MY_input.php contains this code:
class MY_input extends CI_Input
{
public function __construct()
{
parent::__construct();
}
public function save_query($query_array)
{
$CI =&get_instance();
$CI->db->insert('ci_query',array('query_string'=> http_build_query($query_array)));
return $CI->db->insert_id();
}
public function load_query($query_id)
{
$CI =&get_instance();
$rows = $CI->db->get_where('ci_query', array('id' => $query_id))->result();
if (isset($rows[0]))
{
parse_str($rows[0]->query_string, $_GET);
}
}
[![enter image description here][1]][1]}
Now the error is not inside the code but i am placing MY_input.php file. But i don't know what to do and how to solve this issue plus i don't want to change the core framework files of codeigniter.
I think you should use the right camel case file name: MY_Input.php
and class name:
class MY_Input extends CI_Input {
(please notice: the I letter is uppercase)
see documentation:
http://www.codeigniter.com/user_guide/general/core_classes.html

CakePHP pagination maximum limit not working

I am using cakephp 2.x. I am unable to set maximum limit of my record.
Please check my code:
App::uses('AppController', 'Controller');
class BroadcastsController extends AppController {
public $components = array('Paginator');
public function broadcast(){
$this->Paginator->settings = array('limit' => 10, 'order' => array('Broadcast.no_of_user' => 'DESC'), 'group' => 'Broadcast.broadcaster_id');
$popularRooms = $this->Paginator->paginate('Broadcast');
pr($popularRooms); //fetch 200 records
$this->set('popularRooms', $popularRooms);
}
}
Above pr($popularRooms); I am getting 200 records but I want first 50 records and per page showing 10 records. I was using 'maxLimit'=>50 but this code same as 'limit'=>50. Please help me.
In that case, you can use the 'extras' array in your paginator setting
$this->Paginator->settings = array('limit' => 10, 'max_record'=>50, 'order' => array('Broadcast.no_of_user' => 'DESC'), 'group' => 'Broadcast.broadcaster_id');
in your model or AppModel overiding the paginateCount function
class Broadcast extends AppModel {
function paginateCount($conditions, $recursive, $extra) {
$param = array_merge(compact('conditions', 'recursive'), $extra);
$count = $this->find('count', $param);
if (!empty($extra['max_record']) && $count > $extra['max_records']) {
$count = $extra['max_record'];
}
return $count;
}
}
By default CakePHP limits the maximum number of rows that can be fetched to 100.You can adjust it as part of the pagination options like below
public $paginate = array(
// other keys here.
'maxLimit' => 10
);
For you code set the maxLimit like this
$this->Paginator->settings = array('limit' => 10,'maxLimit'=>50,'order' => array('Broadcast.no_of_user' => 'DESC'), 'group' => 'Broadcast.broadcaster_id');
public function list_posts() {
$settings = array(
'limit' => 25, // here
'order' => array(
'Post.title' => 'asc'
)
);
$this->Paginator->settings = $this->settings;
// similar to findAll(), but fetches paged results
$data = $this->Paginator->paginate('Posts');
$this->set('data', $data);
}
I believe you don't have to have $this->Paginator->settings =.
public function list_posts() {
$settings = array(
'limit' => 25, // here
'order' => array(
'Post.title' => 'asc'
)
);
// similar to findAll(), but fetches paged results
$data = $this->Paginator->paginate('Posts');
$this->set('data', $data);
Set maxLimit first in your paginator settings before limit like this:
$this->Paginator->settings = array(
'maxLimit' => 50,
'limit' => 10,
'order' => array('Broadcast.no_of_user' => 'DESC'),
'group' => 'Broadcast.broadcaster_id'
);
Only setting one of them logically does not change anything.

Basic Search Function for cakePHP 2.0 App - Notice (8): Undefined index: search error

Hi I am a newB with cakePHP and I am enjoying it but fnding that there is a stiff learning curve...
Anyway I am trying to get a basic search set up in view that searches only one table for it results. This is for a cakePHP 2.0 app. I am getting the dreaded Notice (8): Undefined index: search error.
Everything else works fine.
Any help would be much appreciated.
Here is my CustomersController code
/**
* index method
*
* #return void
*/
public function index() {
$this->layout = 'front';
// $this->Paginator->settings = $this->paginate;
$this->Paginator->settings = array(
'Customer' => array(
'paramType' => 'querystring',
'limit' => 5,
'order' => array('Customer.created' => 'desc'
)
)
);
$this->Customer->recursive = 0;
$this->set('customers', $this->Paginator->paginate());
/**
* Search Method
*
*
*/
public function search() {
if ($this->request->is('put') || $this->request->is('post')) {
// poor man's Post Redirect Get behavior
return $this->redirect(array(
'?' => array(
'q' => $this->request->data('Customer.searchQuery')
)
));
}
$this->Customer->recursive = 0;
$searchQuery = $this->request->query('q');
$this->Paginator->settings = array(
'Customer' => array(
'findType' => 'search',
'searchQuery' => $searchQuery
)
);
$this->set('customers', $this->Paginator->paginate());
$this->set('searchQuery', $searchQuery);
$this->render('index');
}
Here is my Customer Model
/**
* customer Model
*
*/
class customer extends AppModel {
public $findMethods = array('search' => true);
protected function _findSearch($state, $query, $results = array()) {
if ($state === 'before') {
$searchQuery = Hash::get($query, 'searchQuery');
$searchConditions = array(
'or' => array(
"{$this->alias}.name LIKE" => '%' . $searchQuery . '%',
"{$this->alias}.interest LIKE" => '%' . $searchQuery . '%'
)
);
$query['conditions'] = array_merge($searchConditions, (array)$query['conditions']);
return $query;
}
return $results;
}
Again any help is much appreciated. Thanks in advance!

unable to keep pagination track

Pagination links are shown correctly for 1st time, but when I click 2nd page link the data vanishes.
Here is my code:
Controller
class PostsController extends AppController {
public $components = array('Paginator');
var $paginate = array(
'Post' => array(
'limit' => 5
)
);
public function index() {
//debug("in index");
//$this->render();
$d=$this->data['lower_limit'];
//debug(" df ");
//debug($d);
$lower= $this->data['lower_limit'];
$upper= $this->data['upper_limit'];
$conditions = array('Post.post_id >=' => $lower, 'Post.post_id <=' => $upper);
$this->Paginator->settings = $this->paginate;
$data = $this->Paginator->paginate('Post', $conditions);
$this->set('data', $data);
$this->set('lower_limit',$lower);
$this->set('upper_limit', $upper);
}
}
Model
I have not overridden paginate and pagination count methods.

Categories