Finding previous and next database table item with Query Builder in CodeIgniter 4

Finding previous and next database table item with Query Builder in CodeIgniter 4

Created:28 Jan 2022 21:39:38 , in  Web development

Imagine you have a database table Posts with items like blog posts, news and pages. Each of those items has its unique id and type like "page" or "news". Given an id of a database item, your goal is to find the previous and the next item of the same type relative to the id. In this post I look at how to achieve this with Query Builder queries in CodeIgniter 4.

In your Post model, place add next and previous methods:


namespace App\Models;  
use CodeIgniter\Model;
class PostModel extends Model{
.
.
.
 
  public function next($currentPostId,$type = 'post'){
    return $this -> where(['id >' => $currentPostId,'type' => $type]) -> first();
  }

  // find previous post
  public function previous($currentPostId,$type = 'post'){
    return $this -> where(['id <' => $currentPostId,'type' => $type]) -> first(); 
  }  
.
.
.
}

Now, to find the next and previous item of type "page" relative to your current page with id given by $currentPostId, add the following piece of code in your controller:


$currentPostId = 10; // change this according to you needs
$modelPost = new PostModel();
$previous = $modelPost -> previous($currentPostId,'page');
$next = $modelPost -> next($currentPostId,'page'); 

What's left is, consume $previous and $next variables in a view. If you do you will get a simple two way navigation between pages.

That's it. Now you should be able to write a simple backwards and forwards navigation for your database table items in minutes.

This post was updated on 28 Jan 2022 21:40:27

Tags:  php 


Author, Copyright and citation

Author

Sylwester Wojnowski

Author of the this article - Sylwester Wojnowski - is a sWWW web developer. He has been writing computer code for the websites and web applications since 1998.

Copyrights

©Copyright, 2024 Sylwester Wojnowski. This article may not be reproduced or published as a whole or in parts without permission from the author. If you share it, please give author credit and do not remove embedded links.

Computer code, if present in the article, is excluded from the above and licensed under GPLv3.

Citation

Cite this article as:

Wojnowski, Sylwester. "Finding previous and next database table item with Query Builder in CodeIgniter 4." From sWWW - Code For The Web . https://swww.com.pl//main/index/finding-previous-and-next-database-table-item-with-query-builder-in-codeigniter-4

Add Comment

Allowed BB Code - style tags: [b][/b], [i][/i], [code=text][/code],[code=javascript][/code],[code=php][/code],[code=bash][/code],[code=css][/code],[code=html][/code]


I constent to processing my data given through this form for purposes of a reply by the administrator of this website.

Recent Comments

Nobody has commented on this post yet. Be first!