CodeIgniter Forums

Full Version: CI 4 pagination problem
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
How do I paginate only selected items from a table.

Controller:

PHP Code:
<?php 

namespace App\Controllers;

use 
CodeIgniter\Controller;

class 
Pageusersselect extends Controller
{        
    
public function showusers()
    {
        $Body['title'] = 'Dzielenie wybranych użytkowników na strony';
        
        $pager 
= \Config\Services::pager();
                
        $model 
= new \App\Models\ShowuserselectModel();
        
        $Body
['users'] = $model->PaginateUsers(10);
        $Body['pager'] = $model->pager;
        
        
echo view('showuser/index'$Body);
    }
}

?>

Model:
PHP Code:
<?php 

namespace App\Models;

use 
CodeIgniter\Model;

class 
ShowuserselectModel extends Model
{
    protected $table 'users';
    protected $primaryKey 'id';
    
    
public function PaginateUsers($HowMany)
    {
        $sql "SELECT * FROM users WHERE name LIKE '%n'";
        $Result $this->db->query($sql);
        $Result2 $Result->getRowArray();
        return $Result2;
    }
}

?>

View
PHP Code:
<!doctype html>
<
html lang="pl">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous" />
    <title><?php echo $title?></title>
    <style>
    ul.pagination li 
    {
        margin-left: 5px;
        margin-right: 5px;
    }
    </style>
  </head>
  <body>
    
    <div class="container">
      <div class="row">
        <div class="col-sm-1">
        </div>
        <div class="col-sm-10">
          
        <h1><?php echo $title?></h1>
        
        <table class="table table-bordered">
        <thead>
          <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Address</th>
            <th>City</th>
            <th>Date</th>
            <th>Personal number</th>
          </tr>
        </thead>
        <tbody>
          <?php 
          
if(isset($users))
          {
              foreach($users as $user)
              {
                  echo '<tr>
                    <td>'
.$user['id'].'</td>
                    <td>'
.$user['name'].'</td>
                    <td>'
.$user['address'].'</td>
                    <td>'
.$user['city'].'</td>
                    <td>'
.$user['date'].'</td>
                    <td>'
.$user['personalnumber'].'</td>
                  </tr>'
;
              }
          }
          ?>
        </tbody>
      </table>

      <!-- Pagination -->
      <div class="d-flex justify-content-end">
        <?php if(isset($pager))
        {
            $pager->setPath('pageusersselect');
            echo $pager->makeLinks($page10$TotalRows)
            //echo $pager->links();
        }
        ?>
      </div>

      
        </div>
        <div class="col-sm-1">
        </div>
      </div>
    </div>
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
  </body>
</html> 

Zawsze dostaję błąd: Illegal string offset 'id' w widoku.
I also had problems at first and I ended up doing this.

The code should give you an idea of how to do it, you will notice I am returning $this
so that we can use method chaining.

Don't worry about the group stuff it's because I have custom bootstrap pager templates.

PHP Code:
    // CONTROLLER
    
    
<?php namespace App\Controllers;

use 
App\Models\AuthorModel;
use 
Config\Services;

/**
 * Class Home
 *
 * @package App\Controllers
 */
class Home extends BaseController
{
    private 
$author;

    public function 
index()
    {
        
$pager Services::pager();

        
$this->author = new AuthorModel();
        
        
// This will get all Authors
        
$data = [
            
'authors' => $this->author->getAllAuthors()->paginate(4'group1'),
            
'pager'   => $this->author->pager,
        ];

        echo 
view('test'$data);

        
// This will get all authors by category id
        
$dat = [
            
'authors' => $this->author->getAuthorsByCategory(14)->paginate(4'group1'),
            
'pager'   => $this->author->pager,
        ];

        
//echo view('test', $dat);

        //return view('welcome_message');

    
}

    
//--------------------------------------------------------------------

}
    
// MODEL
    
    // -------------------------------------------------------------------

    /**
     * getAuthors ()
     * -------------------------------------------------------------------
     *
     * Get all authors
     */
    
public function getAuthors()
    {
        
$builder $this->builder();

        
$builder->orderBy('id''ASC');
        
$builder->get();
        
        return 
$this;
    }

    
// -------------------------------------------------------------------

    /**
     * getAuthorsByCategory ()
     * -------------------------------------------------------------------
     *
     * Get all authors by category
     */
    
public function getAuthorsByCategory(int $id)
    {
        
$builder $this->builder();

        
$builder->where('category_id'$id);

        return 
$this;
    }

    
//--------------------------------------------------------------------

    // VIEW
    
    
<!DOCTYPE html>
<
html lang="en">

<
head>

    <
meta charset="UTF-8">

    <
title>Title</title>

    <
link href="<?= base_url('assets/vendor/bootstrap/css/bootstrap.min.css');?>" rel="stylesheet">

</
head>

<
body>

    <
div class="container-fluid">
    <?
php

    
foreach ($authors as $key => $list)
    {
        
//echo $key."<br>";
        
echo $list['id']."<br>";
        echo 
$list['category_id']."<br>";
        echo 
$list['first_name']."<br>";
        echo 
$list['last_name']."<br>";
        echo 
$list['email']."<br>";
        echo 
$list['birthdate']."<br>";
        echo 
$list['added']."<br><br>";
    }

    echo 
$pager->simpleLinks('group1''bs_simple');

    
//echo $pager->makeLinks($page, $perPage, $total, 'bs_simple');

    
?>

    </div>

    <script href="<?= base_url('assets/vendor/jquery/jquery-3.5.1.min.js');?>"></script>
    <script href="<?= base_url('assets/vendor/bootstrap/js/bootstrap.bundle.min.js');?>"></script>

</body>
</html> 

This works like a charm for me.
Thank you, it also worked for me. I'm just wondering how to do it by writing SQL queries?
Just run the queries and than return $this

Which allows you to chain on the paginate method.

So:


PHP Code:
$data['test'] = $model->yourQuery->paginate(10); 

Don't tell your model methods to return any object or array the paginate uses the find method to
return everything.
With Query, you can
1. Get current page: $curPage = $pager->getCurrentPage();
2. In your query, use LIMIT: LIMIT $curPage * $perPage, $perPage