Implementing pagination in codeigniter, can't get count - php

I am having difficulties implementing the codeigniter pagination class. I have created my model, view and controller for getting my news articles and data is echoed in the view successfully.
My problem is that when I attempt to implement pagination it seems like I am unable to get the correct count of fields in my database. Can somebody show me what I have done wrong?
The pagination links display perfectly, but the content echoed does not appear to be limited. How can I count the rows of the query?
Required classes for the pagination are autoloaded
Model:
class News_model extends CI_model {
function get_allNews()
{
$query = $this->db->get('news');
foreach ($query->result() as $row) {
$data[] = array(
'category' => $row->category,
'title' => strip_tags($row->title),
'intro' => strip_tags($row->intro),
'content' => truncate(strip_tags( $row->content),200),
'tags' => $row->tags
);
}
return $data;
}
Controller
// load pagination class
$config['base_url'] = base_url().'/news/index/';
$config['total_rows'] = $this->db->get('news')->num_rows();
$config['per_page'] = '5';
$config['full_tag_open'] = '<div id="pagination">';
$config['full_tag_close'] = '</div>';
$this->pagination->initialize($config);
$viewdata['allnews'] = $this->News_model->get_allNews($config['per_page'],$this->uri->segment(3));
View
<?php if (isset($allnews)): foreach ($allnews as $an): ?>
<?php echo heading($an['title'], 2); ?>
<?php echo $an['content']; ?>
<?php endforeach;
else: ?>
<h2>Unable to load data.</h2>
<?php endif; ?>
<?php echo $this->pagination->create_links(); ?>

In your controller, you're passing parameters to your get_allNews method, but your method doesn't make use of those parameters:
$viewdata['allnews'] = $this->News_model->get_allNews($config['per_page'],$this->uri->segment(3));
So you are getting all records, and expecting the limited result set. You need to change the beginning of your get_allNews method like this:
class News_model extends CI_model {
// make use of the parameters (with defaults)
function get_allNews($limit = 10, $offset = 0)
{
// add the limit method in the chain with the given parameters
$query = $this->db->limit($limit, $offset)->get('news');
// ... rest of method below

Related

Pagination custom url in codeigniter-4

I created a method in a model of CI4 to query a search results. I need to paginate search results but the URL not provide results. I need to standard way for pagination in CI4.
Here is model method -
<?php
public function search($key)
{
$builder = $this->table('apps_common_all');
$builder->Like('name',$key,'after');
$query = $builder->paginate(51);
return $query;
}
?>
controller method is -
<?php
public function result()
{
$key = $this->request->getVar('s');
$apps = new AppsModel();
$data = [
'items' => $apps->search($key),
'pager' => $apps->pager,
];
return view('search/index',$data);
}
?>
Pagination code in view page
<?php if ($pager) :?>
<?php $pagi_path=getenv('pagi_path').'search_result'; ?>
<?php $pager->setPath($pagi_path); ?>
<?= $pager->links() ?>
<?php endif ?>
when pagination link clicked the url not provide results
http://myshahadat.com/demo/apkdownload/search_result?s=a&page=2
and my route is
<?php $routes->get('/search_result', 'Search::result'); ?>

How to pass data controller to view in codeigniter

I am getting user profile fields from the database and want to display in my view but don't know to do this with the master layout.
this is my model
function fetchProfile($id,$page){
$query = $this->db->query("SELECT * FROM staff_master WHERE Id='$id'");
return $query->result();
}
this is my controller:
public function edit($id,$page){
$data['query'] = $this->StaffModel->fetchProfile($id,$page);
$data= array('content'=>'view_staff_edit');
$this->load->view('template_master',$data);
}
I am also trying to find a solution. I am passing user Id and another by URL (get method).
You are overwriting $data['query'] when you assign the array next:
$data['query'] = $this->StaffModel->fetchProfile($id,$page);
$data= array('content'=>'view_staff_edit');
Either do:
$data= array('content'=>'view_staff_edit');
$data['query'] = $this->StaffModel->fetchProfile($id,$page); // note position
Or:
$data = array(
'content' = 'view_staff_edit',
'query' => $this->StaffModel->fetchProfile($id,$page),
);
Access in view via $query and $content.
Unrelated:
You are also missing $page in your query, and its generally a good idea to declare gets as null if not set or you will get a notice: public function edit($id=null,$page=null){
Your overriding your first declaration of variable $data what you can do is to initialize them both at the same time.
Controller
public function edit($id,$page){
$data = array(
'query' => $this->StaffModel->fetchProfile($id,$page),
'content' => 'view_staff_edit'
);
$this->load->view('template_master',$data);
}
Then access it on your View file
<h1><?php echo $content ?></h1>
<?php foreach($query as $result): ?>
<p><?php echo $result->id ?></p>
<?php endforeach; ?>
Try doing something like this:
public function edit($id,$page) {
$data['query'] = $this->StaffModel->fetchProfile($id,$page);
$data['content']= 'view_staff_edit';
$this->load->view('template_master',$data);
}
YOUR MODEL
function fetchProfile($id){
return $this->db->get_where('Id' => $id)->result_array();
}
YOUR CONTROLLER
public function edit($id,$page){
$data = array(
'query' => $this->StaffModel->fetchProfile($id),
'content' => 'view_staff_edit',
);
$this->load->view('template_master',$data);
}
YOUR "template_master" VIEW
<?php foreach ($query as $res){?>
<span><?php echo $res['Id'];?></span> //User html content according to your requirements ALSO you can add all columns retrieved from database
<?php } ?>

Displaying the page titles based on the pages dynamically in codeigniter php

How to display page titles dynamically based on the pages displayed.
Hi i am having a site developed in codeigniter php but the problem is need to display page titles dynamically based on the pages.These pages titles should be fetched from database.Can anyone have any idea how to do this.
Controller:
public function index()
{
$config = array();
$config["base_url"] = base_url('testimonial/index');
$config['total_rows'] = $this->testimonial_model->record_count();//here we will count all the data from the table
$config['per_page'] = 6;//number of data to be shown on single page
$config['first_link'] = 'First';
$config['last_link'] = 'Last';
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data["records2"] = $this->testimonial_model->get_all_testimonials($config["per_page"], $page);
$data['records7'] = $this->index_model->get_all_banners();
$data["links"] = $this->pagination->create_links();//create the link for pagination
$data['mainpage'] = "testimonial";
$this->load->view('templates/template',$data);
}
Model:
function get_all_testimonials($limit, $start)
{
$this->db->limit($limit, $start);
$this->db->select('T.*');
$this->db->from('testimonials AS T');
$this->db->where(array('T.status'=>1));
$q = $this->db->get();
if($q->num_rows()>0)
{
return $q->result();
}
else
{
return false;
}
}
View:
<div class="container">
<div class="row testimonialpage">
<div class="col-md-12 testimonialpage">
<div class="col-md-9 testimonials" >
<div class="testimonialpagetext">
</div>
<?php if(isset($records2) && is_array($records2)):?>
<?php foreach ($records2 as $r):?>
<div class="testimonial1">
<div class="testimonialtext1">
<?php echo $r->description;?>
<ul class="founders">
<li class="founder"><?php echo $r->client_name;?></li>
<li class="founder"><?php echo $r->founder;?></li>
</ul>
</div>
</div>
<?php endforeach ;endif;?>
<div class="pagination"><?php echo $links; ?></div>
</div>
</div>
</div>
For Ex:: Your url is www.example.com/controller/register when you get uri segment(2) means you will get (register). based on this you can identify that you are on the register page. now you can find the title for register page from your database.
Every time i build an application with Codeigniter, i use a Class MY_Controller that extends CI_Controller, inside application/core like bellow:
class MY_Controller extends CI_Controller {
protected $view_data;
function __construct() {
//......
}
}
Any controller inside application/controllers will extend the MY_Controller instead of CI_Controller.
Now in the constructor of MY_Controller you can do something like:
$page = $this->uri->segment(2); (2 or 3 or 4 etc, depends on your structure)
Load your model, execute your query and add the result in $this->view_data like:
$pageTitle = $this->your_model->getPageTitle($page);
$this->view_data['page_title'] = $pageTitle['page_title'];
Example of getPageTitle in your model:
public function getPageTitle($page) {
$qry = $this->db->select('page_title')
->from('pages')
->where('page', $page)
->get();
if ($qry->num_rows() > 0)
return $qry->row_array();
return false;
}
Watch out the sample names i gave, you should change those!
To load your view, pass the variable $this->view_data as parameter and in your view do something like
<title><?= $page_title ?></title>

Why pagination not working correctly?

I have a problem. My Kohana pagination script not working correctly. Must have as follows : [http://127.0.0.1/?page=1], but I have the following - [http://127.0.0.1/index.php/?page=1] and records from database in home page are 2 (total records is 2, i set items_per_page to 1), but must have a 1 record only. Where is the problem?
Controller:
public function action_index()
{
$pagination = Pagination::factory(array(
'total_items'=> Model::factory('index')->get_count(),
'items_per_page' => 1,));
$articles_ = Model::factory('index')->do_magic();
$this->template->page_title = 'Sākums';
$this->template->site_name = Kohana::$config->load('common')->get('site_name');
$this->template->content = View::factory('index/index')
->set('query', $articles_)
->set('pagjinaacija', $pagination->render());
$this->template->styles[] = 'index/index';
}
View
<?php
foreach($query as $row) {
echo '<h2>'.$row['title'].'</h2>';
echo '<p style="margin:0">'.$row['content'].'</p>';
}
echo $pagjinaacija;
?>
And model
Class Model_Index Extends Model {
public function get_count() {
return DB::query(Database::SELECT, 'SELECT COUNT(*) AS count FROM posts')->execute()->get('count');
}
public function do_magic() {
$query = DB::query(Database::SELECT, 'SELECT * FROM posts ORDER By id DESC')->execute()->as_array();
return $query;
}
}
There are 2 problems:
You're not using url rewrite rules to rewrite /index.php?page=2 into /?page=2
You're not actually using the page query parameter to filter your records returned from the db, so it'll display them all.
The pagination object is only used to render a pagination control, not perform the actual filtering of db records.
you maybe set bootstrap.php:
Route::set('index_page','yourcontroller/index(/<page>)', array('page' => '[0-9]+'))
->defaults(array(
'controller' => 'yourcontroller',
'action' => 'index',
));

Codeigniter -> Edit Page

I am getting the following error when I try and access:
domain.co.nz/admin/editpage/home/
I get the following error:
PHP Fatal error: Call to a member function getCMSPage() on a non-object in controllers/home.php on line 22
The issue with this is that I cannot understand why it is being passed back into the main “home” controller - which is the main controller.
All of my models are loaded by default - http://cl.ly/2U1F3a2B0s2K0i3k3g13
Ideal Situation
What I am trying to do with this is load the content into a text area on for editing and when submit is clicked I would like it to go back to the same page with a message saying content updated.
Admin Template
<li><?php echo anchor('#','Edit Pages');?>
<?php if(is_array($cms_pages)): ?>
<ul>
<?php foreach($cms_pages as $page): ?>
<li><a >permalink?>"><?=$page->name?></a></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</li>
Page Model
function updatePage($data){
$data = array('content' => $content);
$this ->db->where('id',$id);
$this->db->update('pages',$data);
}
View:
<?php
//Setting form attributes
$formpageEdit = array('id' => 'pageEdit', 'name' => 'pageEdit');
$formInputTitle = array('id' => 'title', 'name' => 'title');
$formTextareaContent = array('id' => 'content', 'name' => 'content');
?>
<section id = "validation"><?php echo validation_errors();?></section>
<h4><?= $title ?> </h4>
<?php
echo form_open('admin/editpage/'.$page->permalink, $formpageEdit);
echo form_fieldset();
echo form_label ('Content', 'content');
echo form_textarea("content", $page['content']);
echo form_submit('submit','Submit');
echo form_fieldset_close();
echo form_close();
?>
Controller:
function index(){
if($this->session->userdata('logged_in')){
}else{
redirect('admin/home');
}
$page = $this->navigation_model->getCMSPage($this->uri->segment(3));
$data['cms_pages'] = $this->navigation_model->getCMSPages();
$data['title'] = $page->name;
$data['content'] = $this->load->view('admin/editpage', array('page' => $page, TRUE));
$this->load->view('admintemplate', $data);
}
I haven't really tested this yet but it should give you a good start. What you're asking is quite a bit of work to fully code out quickly.
This is the page_model model it's essentially what you posted with a few minor tweaks. Its best to use id's rather than strings. You may also want to do some htmlspecialchars or mysql hijack validation prior to passing these to your DB.
<?php
/**
* This is the Page_model model, this model handles the retrieval and modification of all pages.
*
**/
class Page_model extends CI_Model {
/**
* the getCMSPage function retrieves the data from the db given the ID that was passed via $id.
**/
function getCMSPage($id = NULL) {
$this->db->where('permalink', $permalink);
$query = $this->db->get('pages', 1);
#check to make sure row's were returned, if so continue, otherwise return false.
if ($query->num_rows() > 0){
#set the results into an array and return $row, should return $row['content'], and $row['id'];
#if you were editing more than one page this is where you would use a foreach($query)
$row = $query->result_array();
return $row;
}else{
return false;
}// END if ($query->num_rows() > 0)
}// END function getCMSPage()
}// END Page_model class
?>
This is the site controller and for sake of time i just echo'd your form_textarea straight from the edit function.. you shouldn't do this as it goes against MVC standards. You should create a view for that portion of the section.
<?php
/**
* This is the Site controller, primary controller for your site.
*
**/
class Site extends CI_Controller {
/**
* construct function, in our case we are going to load the Posts_model , you may not want to do this.
*
**/
function __construct()
{
parent::__construct();
#load Page_model, should be located in app/models/page_model.php
$this->load->model('Page_model');
}//END function __construct();
/**
* edit function, this function handles retrieval of the page from the URI, and the page's content for editing.
*
* This function uses $id which auto retrieves the page's ID from the uri. Your URL should look similiar to:
* http://yourdomain.com/site/edit/3/yourunecessaryinformationhere
* everything after the id is not really required but could help with SEO.
*
**/
function edit($id){
#retrieve the page's content in array form.
$page = $this->Page_model->getCMSPage($id);
echo form_textarea("content", $page['content']);
}
}//END Site Class
Keep in mind i wrote this up in 5-10 minutes so its rushed and not very well commented or even tested but itll give you a great head start. This only gives you an example of how to retrieve information from the DB and echo it into a textarea. You would still need to create another function within your page_model to insert/update the information and another snippet of code in your controller to pass the edited content to the model.
You can hit me up on AIM or twitter if you have more questions ThirdGenSup, twitter is #gorelative
// this line
$data['content'] = $this->load->view('admin/editpage', $data);
// needs to be
$data['content'] = $this->load->view('admin/editpage', array('page' => $page, TRUE);

Categories