CI Pagination Back to Posts Link - php

I'm learning CI and latest I've been tasked to do is pagination. So I followed this tutorial as it seemed relatively nicely made and explained. Link
The pagination works and its great. Now I wanted to make a read more under each post, making each post open separately with its full description. That also works, but when I click a link to go back to the pagination index, the list starts from the beginning, no matter which post I clicked. I'm not sure how to add the page I want the return link to take me back so I'll just post this here and hopefully it won't be too hard for someone to tell me.
If someone is confused what I'm after, just look at the last view readmore_paginate. In it, the last link should contain a number back
to the page, but idk how to put or what to put there.
Controller
public function paginate()
{
$config = array();
$config['base_url'] = base_url()."welcome/paginate";
$config['total_rows'] = $this->blog_model->countPosts();
$config['per_page'] = 2;
$config['uri_segment'] = 3;
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0; //TERNARY OPERATOR (? = TRUE) (: = FALSE)
$data['results'] = $this->blog_model->fetchPosts($config['per_page'], $page);
$data['links'] = $this->pagination->create_links();
$this->load->view('header');
$this->load->view("p_content", $data);
$this->load->view('footer');
}
public function readMore_Paginate()
{
$id = $this->input->get('postid');
$data['post'] = $this->blog_model->getSpecificPost($id);
$this->load->view('header');
$this->load->view('readmore_paginate', $data);
$this->load->view('footer');
}
Model
public function countPosts()
{
return $this->db->count_all("Blogposts");
}
public function fetchPosts($limit, $start)
{
$this->db->select('*');
$this->db->from('Blogposts');
$this->db->join('Blogcategories', 'Blogposts.postcatid=Blogcategories.id');
$this->db->limit($limit, $start);
$query = $this->db->get();
if($query->num_rows() > 0)
{
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
View p_content
<div class="col-md-8">
<table class="table">
<tbody>
<?php
foreach ($results as $key) {
echo "<tr><th><h2><kbd><font color='yellow'>".$key->postname."</font></kbd></h2><kbd><font color='lime'>".date("d M Y",strtotime($key->postdate))."</font></kbd> <kbd><font color='cyan'>".$key->catname."</font></kbd></th></tr>";
echo "<tr><td><blockquote>".mb_substr($key->postdesc, 0,80,'UTF-8')."...";?>
read more</blockquote>
<?php } ?>
</tbody>
</table>
<p><?php echo $links; ?></p>
</div>
View readmore_paginate
<div class="col-md-8">
<table class="table">
<tbody>
<?php
foreach ($post as $key) {
echo "<tr><th><h2><kbd><font color='yellow'>".$key['postname'].
"</font></kbd></h2><kbd><font color='lime'>".
date("d M Y",strtotime($key['postdate']))."
</font></kbd> <kbd><font color='cyan'>".
$key['catname']."</font></kbd></th></tr>";
echo "<tr><td><blockquote>".$key['postdesc']."</blockquote>"; ?>
Back to Posts
<?php }
?>
</tbody>
</table>
</div>

Controller
$page = $this->input->get('page') ?
$this->input->get('page') :
$this->uri->segment(3) ?
$this->uri->segment(3) :
0;
$data['results'] = $this->blog_model->fetchPosts($config['per_page'], $page);
$data['links'] = $this->pagination->create_links();
$data['page'] = $page; // add this
view p_content
read more</blockquote>
view readmore_paginate
Back to Posts

Related

Codeigniter Pagination displays links but returns NO Data

If I do not include pagination i.a. comment out $this->db->limit and remove $limit & $start from the get_category_posts() method, the values are displayed as they're meant to in a table. However, as soon as adding the limit the links are displayed but not the 'posts'. I feel there is something wrong with the pagination setup or limit business, or maybe even the position of where I have $this->db->limit (currently undernearth $this->db->from('posts'). I've been up all night trying to get this working and have have no luck on the internet, most people seem to have problems with dislaying links not actually the data itself. If somebody could point me in the direction that would be incredibly appreciated. Thank you.
MODEL:
public function get_category_posts($slug = FALSE, $limit, $start){
if($slug === FALSE){
$this->db->select('post_id, user_id_fk, post_title, post_content, post_date, slug, username');
$this->db->join('category_link_table', 'posts.post_id = category_link_table.post_id_fk');
$this->db->join('category', 'category_link_table.cat_id_fk = category.cat_id');
$this->db->join('users', 'posts.user_id_fk = users.user_id');
$this->db->from('posts');
$this->db->limit($limit, $start);
$this->db->where('category.parent_id', 0);
$query = $this->db->get();
foreach($query->result() as $row){
$data [] = $row;
}
return $data;
//return $query->result_array();
}
}
CONTROLLER:
public function catpage(){
$config['base_url'] = base_url() . "post/catpage";
$config['total_rows'] = $this->post_model->record_count();
$config['per_page'] = 2;
$config['uri_segment'] = 3;
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data['posts'] = $this->post_model->get_category_posts(null, $config['per_page'], $page);
$data['links'] = $this->pagination->create_links();
$this->load->view('templates/header', $data);
$this->load->view('posts/catpage', $data);
$this->load->view('templates/footer');
}
VIEW:
<?php if(isset($posts) & ($posts <> NULL)){
foreach($posts as $post_item): ?>
<tr>
<td><p><?php echo $post_item->post_title; ?></p></td>
<td><p><?php echo $post_item->username; ?></p></td>
<td><p><?php echo $post_item->post_date; ?></p></td>
<td>Rating data</td>
<td>View data</td>
</tr>
<?php
endforeach;
}?>
Also I have a page that deals with individual slugs, so therefore I pass NULL into the methods as it of course requests 3 parameters.
Thank you.

pagination page gives 404 in codeigniter3 framework

I have written pagination code in Codeigniter3 framework, but when I want to go to the second, third and etc. page, it shows me 404 page. Where can be the problem? My routes file:
$route['courses/category/(:any)'] = 'courses/all_courses/$1';
$route['courses/(:any)'] = 'courses/single_course/$1';
My controller:
public function all_courses($categories_slug = NULL, $offset = 0) {
//pagination
$config['base_url'] = base_url() . 'courses/category/'.$categories_slug;
$config['total_rows'] = $this->db->count_all('courses');
$config['per_page'] = 2;
$config['uri_segment'] = 4;
$this->pagination->initialize($config);
$data['title'] = 'Bütün Kurslar Burada';
$data['courses'] = $this->courses_model->get_all_courses($categories_slug, $config['per_page'], $offset);
$this->load->view('templates/header');
$this->load->view('courses/courses', $data);
$this->load->view('templates/footer');
}
My model:
public function get_all_courses($categories_slug = FALSE, $limit = FALSE, $offset = FALSE) {
if($limit) {
$this->db->limit($limit, $offset);
}
<-- and other codes here -->
}
And my view:
<div class="col-md-12 courses_page_btn2">
<nav>
<ul class="pagination">
<li><a><?php echo $this->pagination->create_links(); ?> </a></li>
</ul>
</nav>
</div>
First, in your routes file, your route from courses/category/(:any) is set to route to courses/all_courses/$1, but your controller's all_courses method has a second parameter. So you need to do something about that. I'm guessing that since your pagination is using URI segment 4 that you'll need to adjust your route like this:
$route['courses/category/(:any)/(:num)'] = 'courses/all_courses/$1/$2';
The problem with that route is that if there is no (:num) then you'll get a 404. In most pagination schemes, you're going to want it to default to 1 (the first page). Consider this route instead:
$route['courses/category/(.+)'] = function ($x, $y = 1)
{
return 'courses/all_courses/' . $x . '/' . $y;
};
This will route to your all_courses method, and provide both parameters, even if you leave out the second one.
This pagination works for me with that route:
public function all_courses( $x, $y )
{
$this->load->helper('url');
$this->load->library('pagination');
$pconfig['base_url'] = base_url() . 'courses/category/'.$x;
$pconfig['total_rows'] = 10;
$pconfig['per_page'] = 2;
$pconfig['uri_segment'] = 4;
$this->pagination->initialize($pconfig);
echo $this->pagination->create_links();
}

Delete function always selects same ID - blog - Codeigniter

So, I have been trying to get this delete function to work now for a while.
At the bottom of the foreach I have a delete function. The funtion itself does work, however it always selects the post id of 1.
View
<div><?php foreach($posts as $post) : ?>
<hr>
<h3><?php echo $post['title']; ?></h3>
<div class="row">
<div class="col-md-3">
<img class="post-thumb" src="<?php echo site_url(); ?>posts/image/<?php echo $post['post_image']; ?>">
</div>
<div class="col-md-9">
<small class="post-date">Posted on: <?php echo $post['created_at']; ?> in <strong><?php echo $post['name']; ?></strong></small><br>
<?php echo word_limiter($post['body'], 60); ?>
<br><br>
<p><a class="btn btn-default" href="<?php echo site_url('/posts/'.$post['slug']); ?>">Read More</a></p>
</div>
</div>
<?php echo form_open('/posts/delete/'.$post['id']); ?>
<input type="submit" value="Delete" class="btn btn-danger">
</form>
Controller
public function posts($offset = 0){
// Pagination Config
$config['base_url'] = base_url() . 'admins/posts/';
$config['total_rows'] = $this->db->count_all('posts');
$config['per_page'] = 10;
$config['uri_segment'] = 3;
$config['attributes'] = array('class' => 'pagination-link');
// Init Pagination
$this->pagination->initialize($config);
$data['title'] = 'Latest Posts';
$data['posts'] = $this->post_model->get_posts(FALSE, $config['per_page'], $offset);
$this->load->view('templates/header');
$this->load->view('admins/posts', $data);
$this->load->view('templates/footer');
}
Model
public function delete_post($id){
$image_file_name = $this->db->select('post_image')->get_where('posts', array('id' => $id))->row()->post_image;
$cwd = getcwd(); // save the current working directory
$image_file_path = $cwd."\\assets\\images\\posts\\";
chdir($image_file_path);
unlink($image_file_name);
chdir($cwd); // Restore the previous working directory
$this->db->where('id', $id);
$this->db->delete('posts');
return true;
}
EDIT:
get_posts in model
public function get_posts($slug = FALSE, $limit = FALSE, $offset = FALSE){
if($limit){
$this->db->limit($limit, $offset);
}
if($slug === FALSE){
$this->db->order_by('posts.id', 'DESC');
$this->db->join('categories', 'categories.id = posts.category_id');
$query = $this->db->get('posts');
return $query->result_array();
}
$query = $this->db->get_where('posts', array('slug' => $slug));
return $query->row_array();
}
The function does run and I get a confirmation message, so the only thing I am really confused about is the Id.
The whole thing is written using the CodeIgniter Framework.
Check your get_post model properly. From what you have, it looks like your query will get it's id from the category table.
Try this instead
public function get_posts($slug = FALSE, $limit = FALSE, $offset = FALSE){
if($limit){
$this->db->limit($limit, $offset);
}
if($slug === FALSE){
$this->db->select('posts.id AS id, posts.slug, posts.body, posts.created_at');
$this->db->from('posts, categories');
$this->db->where('categories.id = posts.category_id');
$query = $this->db->get();
return $query->result_array();
}
$query = $this->db->get_where('posts', array('slug' => $slug));
return $query->result_array();
}
Updating your join to LEFT JOIN or simple use WHERE
you are returning only 1 line with row_array() function so you should replace for result_array():
public function get_posts($slug = FALSE, $limit = FALSE, $offset = FALSE){
if($limit){
$this->db->limit($limit, $offset);
}
if($slug === FALSE){
$this->db->order_by('posts.id', 'DESC');
$this->db->join('categories', 'categories.id = posts.category_id');
$query = $this->db->get('posts');
return $query->result_array();
}else{
$query = $this->db->get_where('posts', array('slug' => $slug));
return $query->result_array();
}
}
Thanks to everyone, your answers helped me a lot and I learned a few new things about PHP. I tried implementing your Ideas and they solved the area of the problem I was asking about. In the end I decided to use a simple mysqli query to get the data I needed from the database. mysqli_query($con, "SELECT id,category_id,user_id,title,body,created_at FROM posts Order By id DESC");
May be i am wrong but i think its a foreach syntax issue,
because if you getting same id in all the
rows,
you need to write like,
<?php foreach ($posts as $post) : ?>
instead of,
<?php foreach ($posts as $post) { ?>
//your code goes here
<?php } ?>

How to make pagination with Database category codeigniter?

I am new at codeigniter. I have a problem with codeigniter's pagination.
I tried to search google, youtube and codeigniter documentation but I didn't find anything.
I can implement a simple pagination but I need to create multi pagination with a database in one table.
Anyone that can help me please?
My database:
product:
id category title image
1 burger a a.jpg
2 burger b b.jpg
3 burger c c.jpg
4 pizza d d.jpg
5 pizza e e.jpg
6 pizza f f.jpg
The result that I want is pagination in one page
(pagination category burger by burger,pizza by pizza)
and my url is http://localhost/test-ci1/
Code in Model:
<?php
class Product_model extends CI_Model {
function get_burgers($category="", $limit, $start) {
$this->db->select('*');
$this->db->from('product');
if($category) {
$this->db->where('category',$category);
}
$this->db->limit($limit, $start);
$query = $this->db->get();
return $query->result();
}
function get_total($category="") {
$this->db->select('count(*) AS num_row');
$this->db->from('product');
if($category) {
$this->db->where('category',$category);
}
$this->db->limit(1);
$query = $this->db->get();
return $query->row()->num_row;
}
}
in the Controller:
<?php
class Site extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('product_model','product');
}
public function index()
{
$this->load->model('Product_model');
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data = array();
$per_page =2;
$data["pizza"] = $this->product->get_burgers('pizza', $per_page, $page);
$total_pizza = $this->product->get_total('pizza');
$limit= 2;
$link_pizza = 'http://localhost/test-ci1/pizza';
$data['pagination_pizza'] = $this->pagination($total_pizza,$limit,$link_pizza);
$data["burgers"] = $this->product->get_burgers('burger', $per_page, $page);
$total_burger = $this->product->get_total('burger');
$limit = 2;
$link_burger = 'http://localhost/test-ci1/index/burger';
$data['pagination_burger'] = $this->pagination($total_burger,$limit,$link_burger);
$this->load->view('home_page_view',$data);
}
private function pagination($total ,$per_page ,$link) {
$config['base_url'] = $link;
$config['total_rows'] = $total;
$config['per_page'] = $per_page;
$config['page_query_string'] = TRUE;
$this->pagination->initialize($config);
return $this->pagination->create_links();
}
}
and in my View:
<body>
<h1>Pizza</h1>
<ul>
<?php foreach($pizza as $val) { ?>
<li><?php echo $val->title; ?></li>
<?php } ?>
</ul>
<?php echo $pagination_pizza; ?>
<hr>
<h1>Burger</h1>
<ul>
<?php foreach($burgers as $val) { ?>
<li><?php echo $val->title; ?></li>
<?php } ?>
</ul>
<?php echo $pagination_burger; ?>
</body>
and my result:
Pizza
pizza1
burger2
12>
Burger
burger1
assasa
12>
As I can see you haven't developed your model pagination. You should add a function that does the pagination for you while extracting only the wanted rows from the database.
For your example something like this in your model will do:
function get_burgers($category="", $limit, $start) {
$this->db->select('*');
$this->db->from('product');
if($category) {
$this->db->where('category',$category);
}
$this->db->limit($limit, $start);
$query = $this->db->get();
return $query->result();
}
And in your controller instead of fetching just one burger you should
$data["burgers"] = $this->burger_model->get_burgers($category, $config["per_page"], $page);
And change your foreach in your view to iterate through the burgers

Codeigniter pagination does not work for the second page

Codeigniter pagination does not work for me. It displays page numbers and first 5 search results, but when I click on the page '2' it loads 'search_nok' view with message "Please select your options". Could you please check my code below and help me to find the mistake.
Here is my controller:
public function search($offset = 0) {
$limit = 5;
$this->load->library('form_validation');
$this->load->model('model_x');
$this->form_validation->set_rules('country', 'Country','required');
if($this->form_validation->run()) {
$country = $this->input->post('country');
$this->load->library('pagination');
$config['base_url'] = 'http://localhost/abc/cont/search/'; //where 'http://localhost/abc' is my base url
$config['total_rows'] = 14;
$config['per_page'] = 5;
$data['pagination'] = $this->pagination->initialize($config);
if ($this->model_x->did_search($country, $limit, $offset)){
$data["results"] = $this->model_x->did_search($country, $limit, $offset);
$this->load->view("search_ok",$data);
}
}
else
{
$data['message'] = 'Please select your options.';
$this->load->view("search_nok",$data);
}
}
Here is my view:
<?php
echo $this->pagination->create_links();
foreach($results as $row){
$country = $row['country'];
$city = $row['city'];
?>
<table>
<tr>
<td >
<b><?php echo $country; ?></b>
</td>
<td>
<b><?php echo $city; ?></b>
</td>
</tr>
</table>
<?php }?>
I think you are confused about Pagination. First of all, technically all of the pagination stuff:
<?php
$this->load->library('pagination');
$config['base_url'] = 'http://localhost/abc/cont/search/'; //where 'http://localhost/abc' is my base url
$config['total_rows'] = 14;
$config['per_page'] = 5;
should be in your controller, secondly, you should actually be limiting the results in your model as well, since you haven't shown your model I will come up with an example
$this->db->limit ($limit $offset //these will be defined in your controller)
$data = $this->db->get('whatever_table')->whatever_result_type.
return $data
you should define $limit in your controller and pass it over your your model function as a parameter that the function accepts
the controller should also have $offset and $limit defined
public function search($offset = 0) {
$limit = 5;
when you call your model make sure to pass these over
$this->model_x->did_search($country, $limit, $offset);
then instead of just $this->pagination->initialize($config);
do this(still in your controller remember):
$data['pagination'] = $this->pagination->initialize($config);
then echo pagination wherever you want it in your view

Categories