Methods inside model getting executed more than twice in codeigniter - codeigniter

I have a Model, that i am call inside a Controller function. I am calling viewcategory function at page loads and calling some module function but why its getting executed 2-3 times ?
CategoryPost Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class CategoryPost extends CI_Controller {
function viewcategory($name)
{
$this->load->database();
$this->load->helper("url");
$this->load->helper('form');
$this->load->library('table');
$this->load->library('pagination');
$this->load->model('categorypostmod');
$this->load->model("site_model");
$page = $this->uri->segment(5);
$categCount = $this->categorypostmod->getCategorycount($name);
$config['base_url'] = "http://localhost/b3/index.php/CategoryPost/viewcategory/" . $name . "/page/";
$config['per_page'] = 2;
$config['num_links'] = 5;
log_message('info', 'count is ' . $categCount);
$config['total_rows'] = $categCount;
$config['full_tag_open'] = '<ul class="pagination">';
$config['full_tag_close'] = '</ul>';
$config['use_page_numbers'] = TRUE;
$config['next_link'] = 'Next';
$config['next_tag_open'] = '<li class="next page">';
$config['next_tag_close'] = '</li>';
$config['prev_link'] = ' Previous';
$config['prev_tag_open'] = '<li class="prev page">';
$config['prev_tag_close'] = '</li>';
$config['cur_tag_open'] = '<li class="active"><a href="">';
$config['cur_tag_close'] = '</a></li>';
$config['num_tag_open'] = '<li class="page">';
$config['num_tag_close'] = '</li>';
$config['uri_segment'] = 5;
$data['query'] = $this->categorypostmod->getCategorypost($name, $config['per_page'], $page);
// $records = $this->db->get('post', $config['per_page'], $page);
$this->pagination->initialize($config);
$this->load->view('script');
$this->load->view('head');
$this->load->view('cat_content_list', $data);
$this->load->view('aside');
$this->load->view('bottom');
$this->load->model('Aside_mod');
if($this->Aside_mod->check_cat_exists($name)){
$this->Aside_mod->update_cat_count($name, $this->Aside_mod->get_cat_count($name)+1);
}
else{
$this->Aside_mod->add_cat_views($name);
}
}//end function
}//end class
Model
class Aside_mod extends CI_Model {
function __construct() {
parent::__construct();
$this->load->database();
}
function save_cat($name){
if($this->check_cat_exists($name)){
$this->update_cat_count($name,$this->Aside_mod->get_cat_count($name)+1);
}
else{
$this->add_cat_views($name);
}
}
function getpopular_categ(){
$this->db->select('tags');
$this->db->from('post');
return $this->db->count_all_results();
}
function add_cat_views($name){
$data = array(
'tagname' => $name,
'count' =>0
);
return $this->db->insert('tagcount', $data);
}
function update_cat_count($name,$countval){
$data = array(
'count' =>$countval
);
$this->db->where('tagname', $name);
$this->db->update('tagcount', $data);
}
function check_cat_exists($name){
$exist=false;
$this->db->select('tagname');
$this->db->where('tagname',$name);
$query = $this->db->get('tagcount');
if($query->num_rows() > 0){
log_message('info', 'Exists ');
$exist=true;
}
return $exist;
}
function get_cat_count($name){
$this->db->where('tagname',$name);
$query=$this->db->get('tagcount');
$co=0;
if ($query->num_rows() > 0){
foreach ($query->result() as $row)
{
$co= $row->count;
}
}
return $co;
}
function getCategorypost($catname,$lim1,$lim2){
$this->db->cache_on();
$this->db->select('*')->from('post')->like('post.tags',$catname)->limit($lim1, $lim2);
$query = $this->db->get();
return $query;
}
}

Only going by what you have provided so far... Looking at your controller- you are calling the model 2-3 times depending upon the result of your IF statement near the end!
So it's doing what you are telling it to do!
It would make more sense to refactor your Controller so you just make a single call to the model and have all that if,else code performed in the model.
So in your Model - create a new method to contain the code ( as a first iteration and could be refined)
public function save_cat($name)
{
if($this->check_cat_exists($name)) {
$this->update_cat_count($name, $this->get_cat_count($name)+1);
}
else {
$this->add_cat_views($name);
}
}
Then your controller becomes...
<snip>
$this->load->view('aside');
$this->load->view('bottom');
$this->load->model('aside_mod');
$this->aside_mod->save_cat($name);
}//end function
}//end class

Related

Why do i get the same values in all pages in CI pagination?

I'm kinda new in CI and i'm trying to create a proper pagination for my page.
I have the following model and controller and even if i manage to get the pagination links, when i visit the other pages i get the same entries again and again.
I also have applied an Ajax "GET" filtering for fetching results from db and i managed to reuse the url parameters when i change pages.
The problem is that i don't know if i should try to create an infinite scroll function or maintain the default CI pagination.
I'd like to hear your opinions too!
Thank you in advance!
public function get_filtered_pets($limit, $start){
$this->db->order_by('pet_created_at', 'DESC');
$this->db->join('users', 'users.user_id = pets.pet_user_id');
$this->db->join('pet_categories', 'pet_categories.pet_category_id = pets.category_id');
$pet_data = array();
if ( $this->input->get('petStatus') ) {
$pet_data['pet_status'] = $this->input->get('petStatus');
}
if ( $this->input->get('petCategory') ) {
$pet_data['category_id'] = $this->input->get('petCategory');
}
if ( $this->input->get('petGender') ) {
$pet_data['pet_gender'] = $this->input->get('petGender');
}
if ( !empty($pet_data) ) {
$this->db->where($pet_data);
}
$query = $this->db->get('pets');
if ($start > 0) {
$this->db->last_query();
}
return $query->result_array();
}
And my controller
public function index(){
$query = $this->db->get('pets');
$pet_num = $query->num_rows();
$config = array();
$config["base_url"] = base_url() . "pets/index/";
$config["total_rows"] = $pet_num;
$config["per_page"] = 12;
$config['use_page_numbers'] = TRUE;
$config['reuse_query_string'] = TRUE;
$config['attributes'] = array('class' => 'page-link');
$config["full_tag_open"] = '<ul class="pagination">';
$config["full_tag_close"] = '</ul>';
$config["first_link"] = "«";
$config["first_tag_open"] = "<li>";
$config["first_tag_close"] = "</li>";
$config["last_link"] = "»";
$config["last_tag_open"] = "<li>";
$config["last_tag_close"] = "</li>";
$config['next_link'] = '>';
$config['next_tag_open'] = '<li>';
$config['next_tag_close'] = '<li>';
$config['prev_link'] = '<';
$config['prev_tag_open'] = '<li class="page-item">';
$config['prev_tag_close'] = '<li>';
$config['cur_tag_open'] = '<li class="page-item active"><a class="page-link" href="#">';
$config['cur_tag_close'] = '</a></li>';
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data['pets'] = $this->pet_model->get_filtered_pets($config["per_page"], $page);
$data["links"] = $this->pagination->create_links();
//View files
$this->load->view('templates/header', $data);
$this->load->view('pets/index', $data);
$this->load->view('templates/footer', $data);
}
You are not using the value of $limit and $start nowhere. See Limiting or Counting Results.
You should:
public function get_filtered_pets($limit, $start){
$this->db->limit($limit, $start);
/* ... */
return $query->result_array();
}
And also, when calling this function you have to multiply: per_page * page, to get the offset (starting index).
$this->pet_model->get_filtered_pets($config["per_page"], $page * $config["per_page"])
To count results correctly, I normally have two functions on model: "get($search, $offset)" and "count($search)".
The function count has exactly the same code on get, except the select fields.
See this code, I think you will get it: https://pastebin.com/dZG90Lzm.
ps: There's ways to optimize it and avoid duplicate code.

pagination not working in codeigniter

my controller page
public function index() {
$data['error']="";
$data['h']="";
$this->load->library('pagination');
$config['base_url'] = base_url().'Imagec/index';
$config['total_rows'] = 10;
$config['per_page'] = 2;
$config["uri_segment"] = 4;
$this->pagination->initialize($config);
$page = ($this->uri->segment(4)) ? $this->uri->segment(4) : 0;
$data['h']=$this->Inserts_model->select($config["per_page"], $page);
$data["links"] = $this->pagination->create_links();
$this->load->view('select_view', $data);
}
my mode page
public function select($limit, $start)
{
$this->db->limit($limit, $start);
$query = $this->db->get('student');
return $query->result();
}
my view page
<p><?php echo $links; ?></p>
here all my code here when click on links the NOT FOUND error occur's
Try this 100% will work
Controller :
public function index() {
$data['error'] = "";
$data['h'] = "";
$this->load->library('pagination');
$data['h'] = $this->inserts_model->select();
$config['base_url'] = base_url() . '/index.php/imagec/index';
$config['total_rows'] = count($data['h']);//it will give you total no of records
$config['per_page'] = 2;
$config["uri_segment"] = 3;
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data['h'] = $this->inserts_model->select($config["per_page"], $page);
$data["links"] = $this->pagination->create_links();
// echo "<pre>";print_r($data);die;
$this->load->view('select_view', $data);
}
Model :
public function select($limit=0, $start=0) {
if (empty($start) && !empty($limit)) {
$this->db->limit($limit);
}
if (!empty($start) && !empty($limit)) {
$this->db->limit($limit, $start);
}
$query = $this->db->get('student');
return $query->result();
}

how to send value through function in codeigniter

public function index_pagination(){
$this->load->library("pagination");
$config = array();
$config["base_url"] = base_url("index/index");
$config["total_rows"] = $this->index_model->record_count();
$config["per_page"] = 2;
$config["uri_segment"] = 3;
// Styling pagination
$config["full_tag_open"] = "<ul class='pagination'>";
$config["full_tag_close"] = "</ul>";
$config["next_tag_open"] = "<li>";
$config["next_tag_close"] = "</li>";
$config["prev_tag_open"] = "<li>";
$config["prev_tag_close"] = "</li>";
$config["num_tag_open"] = "<li>";
$config["num_tag_close"] = "</li>";
$config["cur_tag_open"] = "<li class='active'><a>";
$config["cur_tag_close"] = "</li></a>";
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data["page"] = $this->index_model->fetch_products($config["per_page"], $page);
$data["links"] = $this->pagination->create_links();
}
public function index(){
$this->index_pagination();
$this->load->view('frontend/index', $data);
}
How can I pass $data["page"] and $data["links"] from index_pagination() function to my view file through index function?
You can do like this..
<?php
public function index(){
$data = array();
$data = $this->index_pagination();
$this->load->view('frontend/index', $data);
}
public function index_pagination(){
$this->load->library("pagination");
$config = array();
$config["base_url"] = base_url("index/index");
$config["total_rows"] = $this->index_model->record_count();
$config["per_page"] = 2;
$config["uri_segment"] = 3;
// Styling pagination
$config["full_tag_open"] = "<ul class='pagination'>";
$config["full_tag_close"] = "</ul>";
$config["next_tag_open"] = "<li>";
$config["next_tag_close"] = "</li>";
$config["prev_tag_open"] = "<li>";
$config["prev_tag_close"] = "</li>";
$config["num_tag_open"] = "<li>";
$config["num_tag_close"] = "</li>";
$config["cur_tag_open"] = "<li class='active'><a>";
$config["cur_tag_close"] = "</li></a>";
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data["page"] = $this->index_model->fetch_products($config["per_page"], $page);
$data["links"] = $this->pagination->create_links();
return $data;
}
I wrote two simple function in my controller, and used it. This is may not answer of your question but by using this at least you go DRY.
/**
* This function used provide the pagination resources
* #param {string} $link : This is page link
* #param {number} $count : This is page count
* #param {number} $perPage : This is records per page limit
* #return {mixed} $result : This is array of records and pagination data
*/
function paginationCompress($link, $count, $perPage = 10) {
$this->load->library ( 'pagination' );
$config ['base_url'] = base_url () . $link;
$config ['total_rows'] = $count;
$config ['uri_segment'] = SEGMENT;
$config ['per_page'] = $perPage;
$config ['num_links'] = 5;
$config ['full_tag_open'] = '<nav><ul class="pagination">';
$config ['full_tag_close'] = '</ul></nav>';
$config ['first_tag_open'] = '<li class="arrow">';
$config ['first_link'] = 'First';
$config ['first_tag_close'] = '</li>';
$config ['prev_link'] = 'Previous';
$config ['prev_tag_open'] = '<li class="arrow">';
$config ['prev_tag_close'] = '</li>';
$config ['next_link'] = 'Next';
$config ['next_tag_open'] = '<li class="arrow">';
$config ['next_tag_close'] = '</li>';
$config ['cur_tag_open'] = '<li class="active"><a href="#">';
$config ['cur_tag_close'] = '</a></li>';
$config ['num_tag_open'] = '<li>';
$config ['num_tag_close'] = '</li>';
$config ['last_tag_open'] = '<li class="arrow">';
$config ['last_link'] = 'Last';
$config ['last_tag_close'] = '</li>';
$this->pagination->initialize ( $config );
$page = $config ['per_page'];
$segment = $this->uri->segment ( SEGMENT );
return array (
"page" => $page,
"segment" => $segment
);
}
function userListing()
{
$this->load->model('user_model');
$this->load->library('pagination');
$count = $this->user_model->userListingCount();
$returns = $this->paginationCompress ( "userListing/", $count, 5 );
$data['userRecords'] = $this->user_model->userListing($returns["page"], $returns["segment"]);
$this->load->view('includes/header');
$this->load->view("users", $data);
$this->load->view('includes/footer');
}
Try this with your piece of code.
You can go for this repository to understand more https://github.com/kishor10d/Admin-Panel-User-Management-using-CodeIgniter

Codeigniter pagination displays extra num links

When I search for a pages in my categories it displays the result of what pages are in that category.
For testing I have set the limit per page to 1 on my search_for
function.
Question/Problem: If there a only 2 pages that show up in result for some reason the pagination links display 5 links where it should only display 2 pagination links.
functions for model are on controller for testing.
I think the problem lies where the db->like and db->or_like in model. Why does it display 5 pagination links when should only display 2 if only 2 results found.
Controller
<?php
class Category_search extends Catalog_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$data['title'] = "Search Category";
$data['categories'] = array();
$results = $this->get_categories();
foreach ($results as $result) {
$data['categories'][] = array(
'category_id' => $result['category_id'],
'name' => $result['name']
);
}
$this->load->library('form_validation');
$this->form_validation->set_rules('page', 'Category');
$this->form_validation->set_rules('name', 'Name');
if ($this->form_validation->run() == FALSE) {
$this->load->view('theme/default/template/pages/search_category_view', $data);
} else {
redirect('pages/category_search/search_for' . '/' . $this->input->post('category'));
}
}
public function search_for($offset = NULL) {
$data['title'] = "Caregory Results";
$data['heading_title'] = "Search" .' - '. $this->get_category_name($this->uri->segment(4));
$data['pages'] = array();
$this->load->library('pagination');
$limit = 1;
$config['base_url'] = base_url('pages/category_search/search_for') .'/'. $this->uri->segment(4);
$config['total_rows'] = $this->get_total_pages();
$config['per_page'] = $limit;
$config['use_page_numbers'] = TRUE;
$config['uri_segment'] = 5;
$config['num_links'] = "16";
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] ="</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
$this->pagination->initialize($config);
$page = ($this->uri->segment(5)) ? $this->uri->segment(5) : 0;
$results = $this->get_pages_within($config['per_page'], $page);
$this->load->model('catalog/tool/model_tool_image');
foreach ($results as $result) {
$data['pages'][] = array(
'category_id' => $result['category_id'],
'parent_id' => $result['parent_id'],
'name' => $result['name'],
'description' => $result['description'],
'image' => $this->model_tool_image->resize($result['image'], 280, 200)
);
}
$data['pagination'] = $this->pagination->create_links();
$this->load->view('theme/default/template/pages/search_category_search_for_view', $data);
}
// Todo move model functions to new model file when complete
public function get_categories() {
$this->db->select('*');
$this->db->from($this->db->dbprefix . 'category c', 'LEFT');
$this->db->join($this->db->dbprefix . 'category_description cd', 'cd.category_id = c.category_id', 'LEFT');
$query = $this->db->get();
return $query->result_array();
}
public function get_pages_within($limit, $offset) {
$this->db->select('*');
$this->db->from($this->db->dbprefix . 'page_to_category p2c', 'LEFT');
$this->db->join($this->db->dbprefix . 'page p', 'p.page_id = p2c.page_id', 'LEFT');
$this->db->join($this->db->dbprefix . 'page_description pd', 'pd.page_id = p2c.page_id', 'LEFT');
$this->db->like('p2c.parent_id', (int)$this->uri->segment(4));
$this->db->or_like('p2c.category_id', (int)$this->uri->segment(4));
$this->db->limit($limit, $offset);
$query = $this->db->get();
return $query->result_array();
}
public function get_total_pages() {
return $this->db->count_all($this->db->dbprefix . 'page');
}
public function get_category_name($category_id = 0) {
$this->db->where('category_id', (int)$category_id);
$query = $this->db->get($this->db->dbprefix . 'category_description');
if ($query->num_rows() > 0) {
$row = $query->row();
return $row->name;
} else {
return FALSE;
}
}
}
I suppose 5 is all the table rows with no where/like filter and it probably come from this function that count everything:
public function get_total_pages() {
return $this->db->count_all($this->db->dbprefix . 'page');
}
Here you should add the same where clause.
Simple fix thanks to #KyleK suggestion I copied the code from the get_pages_within function and then returned return $query->num_rows();
All working
public function get_total_pages() {
$this->db->select('*');
$this->db->from($this->db->dbprefix . 'page_to_category p2c', 'LEFT');
$this->db->join($this->db->dbprefix . 'page p', 'p.page_id = p2c.page_id', 'LEFT');
$this->db->join($this->db->dbprefix . 'page_description pd', 'pd.page_id = p2c.page_id', 'LEFT');
$this->db->like('p2c.parent_id', (int)$this->uri->segment(4));
$this->db->or_like('p2c.category_id', (int)$this->uri->segment(4));
$query = $this->db->get();
return $query->num_rows();
}

code igniter pagination for displaying specific data from database?

I want to display some specific data from database through pagination using CI.but pagination by default passess parameter in function which creates problem for me.
Here is my Controller
function page($catagoryid){
$this->load->library('pagination');
$config['base_url'] = base_url().'index.php/pagination/page/';
$count = $this->db->query("select * from tbl_products where category_id='$categoryid'");
$total=$count->num_rows();
$per_page = 4;
$config['total_rows'] = $total;
$config['per_page'] = $per_page;
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
$this->load->model("mpagination");
$data['list'] = $this->mpagination->get_s(,$categoryid,$config['per_page'],$this->uri->segment(3));
if ($data['list']!== null){
$this->load->view('pagination_view', $data);
}
else {
$this->load->view('noresult');
}
}
Here is my Model
function get_s($categoryid,$num, $offset) {
$this->db->select ('*');
->where('category_id',$categoryid); // field name
$sql = $this->db->get('tbl_products',$num, $offset); // table name
if ($sql->num_rows () >0) {
return $sql->result();
}
else {
return null;
}
}
Here is my view
<?php
foreach($list as $row):?>
<?php echo $row->_prduct_id." ".$row->name." ".$row->description;?>
<br/>
<?php endforeach;?>
<br/>
<?php echo $pagination; ?>
This code work at first but when i clicked on second link of pagination it will not work because by default pagination sends its value to url as parameter and doesnot show data.
what can i do?
I didn't understand your code properly but this is the way you need to do pagination.
public function page($category_id)
{
$result = $this->model_file->model_function($category_id);
$start_index = 0;
$total_rows = count($result);
$items_per_page = 10;
$filtered = array_splice($result,$start_index,$items_per_page);
$model['data'] = $filtered;
$model['page_link'] = create_page_links (base_url()."/controller_file_name/page", $items_per_page, $total_rows);
$this->load->view('view_file_name_path',$model);
}
function create_page_links($base_url, $per_page, $total_rows) {
$CI = & get_instance();
$CI->load->library('pagination');
$config['base_url'] = $base_url;
$config['total_rows'] = $total_rows;
$config['per_page'] = $per_page;
$CI->pagination->initialize($config);
return $CI->pagination->create_links();
}
Try like this
public function index($offset = 0)
{
$language_id = 1;
$this->load->library('pagination');
$limit = 10;
$total = $this->legend_model->get_legend_count($language_id);
$config['base_url'] = base_url().'legend/index/';
$config['total_rows'] = $total;
$config['per_page'] = $limit;
$config['uri_segment'] = 3;
$config['first_link'] = '<< First';
$config['last_link'] = 'Last >>';
$config['next_link'] = 'Next ' . '>';
$config['prev_link'] = '<' . ' Previous';
$config['num_tag_open'] = '<span class="number">';
$config['num_tag_close'] = '</span>';
$config['cur_tag_open'] = '<span class="current"><a href="#">';
$config['cur_tag_close'] = '</a></span>';
$this->pagination->initialize($config);
$data['offset'] = $offset;
$data['legends'] = $this->legend_model->get_legend($language_id, $limit, $offset);
$this->template->write('title', 'Legend : Manage Legend');
$this->template->write_view('content', 'legend/index', $data);
$this->template->render();
}

Resources