Quantcast
Channel: CodeIgniter Forums - All Forums
Viewing all 14343 articles
Browse latest View live

DatabaseException: You must set the database table to be used with your query

$
0
0
I get the following error
CodeIgniter\Database\Exceptions\DatabaseException
You must set the database table to be used with your query
Using the code below ( it seems to me that tables name are set )

Any hint to fix the issue? Thanks a lot

Code:
public function index(): string
{
   $model = new RegisterModel();
   $total->registrations = $model->countRegistrations();
   $this->viewData['total'] = $total;
   return view('pages/public/registers/civil/main', $this->viewData);
}
In the Model is:
Code:
namespace App\Models\Public\Registers\Civil;
use CodeIgniter\Model;
class RegisterModel extends Model
{
    protected $DBGroup = 'registers';
    protected $table_register      = 'rci_combinations';
    protected $table_registrations = 'rci_registrations';
    protected $table_aircrafts    = 'rci_aircrafts';
    protected $table_models        = 'aircraft_models';
    protected $table_manufacturers = 'aircraft_manufacturers';
    protected $table_pictures      = 'rci_images';
...
...
public function countRegistrations($p = NULL, $id = NULL)
{
    $builder = $this->db->table("$this->table_pictures");
    $builder->select("
        $this->table_register.id
        ");
       
    $builder->from("$this->table_register");
    $builder->join("$this->table_registrations", "$this->table_registrations.rid = $this->table_register.rid");
    $builder->join("$this->table_pictures", "$this->table_register.id = $this->table_pictures.id");
    $builder->join("$this->table_relations", "$this->table_relations.register_id = $this->table_register.id",'left');
    $builder->where("$this->table_registrations.icao_id", '115');

    if($p == 'operators')
    {
        $builder->groupBy("$this->table_register.rid");
        $builder->where("$this->table_relations.operator_id", $id);
    }
    $query = $builder->countAllResults();
    return $query;
}

Codeigniter 4 and DB hosted in Kubernetes

$
0
0
Hello, I am beating my head against the wall trying to figure out what I am doing wrong... 
I setup a PostgreSQL database in my Kubernetes cluster, have it exposed through LoadBalancer.  I can connect from Python and PGAdmin just fine.
Configured CI to connect with the same config used in Python and PGAdmin:
Code:
    public array $default = [
        'DSN'        => '',
        'hostname'  => '192.168.1.240',
        'username'  => 'xxxx',
        'password'  => 'xxxx',
        'database'  => 'xxxx',
        'schema'    => 'public',
        'DBDriver'  => 'Postgre',
        'DBPrefix'  => '',
        'pConnect'  => false,
        'DBDebug'    => true,
        'charset'    => 'utf8',
        'swapPre'    => '',
        'failover'  => [],
        'port'      => '5432',
        'dateFormat' => [
            'date'    => 'Y-m-d',
            'datetime' => 'Y-m-d H:i:s',
            'time'    => 'H:i:s',
        ],
    ];

All I get is "No route to host" Unable to connect to Database... 

What am I missing?  

Best Practices for Implementing Role-Based Access Control in CodeIgniter 4

$
0
0
Hi Everyone,
I'm working on a web application using CodeIgniter 4 and need some advice on implementing a secure and scalable Role-Based Access Control (RBAC) system. I’ve come across different approaches, but I’m looking for guidance on the most efficient and maintainable way to handle user roles and permissions.
Here’s a bit of context:
  • My application requires user roles like Admin, Manager, and User, each with different access levels.
  • Users need varying permissions to access controllers, methods, and specific resources.
  • I want a solution that’s easy to manage, scalable for future roles, and minimizes database queries.
I’ve seen solutions that involve:
  1. Storing roles and permissions in the database and checking access in controllers using middleware.
  2. Using filters to handle permissions, but I’m unsure how to best configure them for dynamic role checks.
  3. Extending BaseController to handle access control.
Questions I have:
  • What’s the best approach for integrating RBAC in CodeIgniter 4 while maintaining performance?
  • Is it better to handle role checks in controllers, middleware, or elsewhere?
  • Should I use a third-party library, or is it better to create a custom solution?
  • Are there any pitfalls I should be aware of when implementing RBAC in CI4?
If anyone has a sample implementation or can point me to a detailed guide, it would be greatly appreciated! Any best practices for azure interview questions or personal experiences would also be helpful.
Thanks in advance for your help!

anchor() with multiple subdomains/hostnames

$
0
0
I'm using multiple subdomains and hostnames within an application. It looks like the anchor function uses the current URL to build the link element, however, it doesn't respect the current subdomain.  So, while using a.example.com, the link will point to example.com domain.

The current URL's host is the "example.com" domain, so from the anchor output, that's not unexpected, I suppose, but incorrect...

Request for Help: CodeIgniter 3 to 4 Migration

$
0
0
I'm currently working on migrating a website from CodeIgniter 3 to CodeIgniter 4 and facing several challenges. I have very limited experience with this framework and have been using AI tools to assist me.
Current Situation:
  • The website is organized into Frontend and Backend sections
  • I've already migrated CSS, JS, and images to the public directory
  • The homepage has animations that aren't loading properly (likely JavaScript-related)
  • Some pages don't follow the standard MVC (Model-View-Controller) structure
Specific Issues:
  1. I'm unsure if I've correctly placed all CSS and JavaScript files
  2. Pages without the standard MVC structure aren't working
  3. Homepage animations are broken
I would greatly appreciate any guidance on:
  • Properly organizing assets in CodeIgniter 4
  • Handling pages that don't follow the standard MVC pattern
  • Troubleshooting the JavaScript animation issues
Thank you in advance for any assistance you can provide!
the structure

[Website Showcase] A Travel Blog Built from Scratch with CodeIg

$
0
0
Hey everyone! ?
I’d like to showcase my travel-related blog/website, TravelStyleMate, which I built entirely from scratch using the CodeIgniter 4 framework and the Auth System From Shield My goal was to create a fast, optimized, and feature-rich travel platform while maintaining full control over performance and design.

? Features & Highlights:
Custom-Built Travel Blog – Not based on WordPress, but designed to function like a modern blog with full flexibility.
Sections for Blog Posts, Captions & Destinations – Structured content to make navigation easy and engaging.
Optimized for Speed & Performance – Implemented every possible speed optimization, ensuring fast load times. (It shows 80+ in Google Page Speed Now)
Unused CSS Removal System – Automatically scans views and removes unused CSS using
Code:
sabberworm/php-css-parser
.
Bootstrap-Based with Customizations – Built on Bootstrap but customized to match my requirements.
Table of Contents System – Similar to Rank Math’s TOC, integrated into the content dynamically.
SEO-Friendly & Scalable – Focused on growth with SEO-friendly structures.

Future Plans:
I’m continuously improving the site, adding more features, and fine-tuning the user experience. Would love to hear feedback from the community!
Still not getting 90+ page speed? If you have any suggestions, give feedback.

How to Write API Documentation That Developers Will Love

Nested arrays in parser with conditional rendering

$
0
0
Hi,

I´d like to apply a conditional rendering in a nested iterator:
Code:
{parent}
  {children}
    {if $child->someAttribute == "1"}
      HELLO!
    {endif}
  {children}
{/parent}

I tried to use a static index and it works, but would be necessary to know the current iterator index
Code:
{parent}
  {children}
    {if $parent[0]->children[0]->someAttribute == "1"}
      HELLO!
    {endif}
  {children}
{/parent}
If there was something like:
Code:
{if $parent[$parent_idx]->children[$children_idx]->someAttribute == "1"}

Is this possible? There is any workaround?
Thanks in advance!

How to add data when loading CI4 library

$
0
0
Hi Team,
I have had to bite the upgrade bullet. Generally I find the docs excellent, but I have hit a small issue with upgrading a CI3 load->library call which includes an array of parameters
ie
            //Load library
            $config['upload_path'] = $upload_folder;
            $config['allowed_types'] = 'jpeg|jpg|png';
            $config['max_size'] = $max_size * 1024;
            $config['file_name'] = $col.'_'.$row; //Temp name
       
            $this->load->library('upload', $config);
            $this->load->library('image_lib');
I can find no help on this migration.
Can anyone point me in the right direction please or explain what I need to refactor perhaps?
TIA, Paul

Using a sql alias within a model's find() function

$
0
0
I have a table that containes both Engligh and Spanish translations. The Spanish translation is a bit of an afterthough... so I am looking for an easy way to implement a language change accross my sight. What I am doing now is performing a callback after a model's find() function to unset all the translated columns and return only the sessions language:
test_en ---> test
unset(test_en)
unset(test_es)

Is there a way to implement an alias in the beforeFind callback? Can I modify the find query to select 'test_'.$_SESSION['lang'] AS test

Essentually, I would like to not fetch both columns just to unset the ones I don't want.

Here is my test model I am trying to play with:


PHP Code:
<?php 
namespace App\Models;
use 
CodeIgniter\Model;
class 
TestModel extends Model
{
    protected $table      'tblzz';
    protected $primaryKey 'id';
    protected $useAutoIncrement true;
    protected $returnType    'array';
//TODO: $useSoftDeletes = true; causes ->find() to return null
    protected $useSoftDeletes false;
    protected $allowedFields = ['id',
                                'test_en',
                                'test_es',
                                'date'];
    // Callbacks
    protected $allowCallbacks true;
    protected $beforeInsert  = [];
    protected $afterInsert    = [];
    protected $beforeUpdate  = [];
    protected $afterUpdate    = [];
    protected $beforeFind    = ['pickLang'];
    protected $afterFind      = ['parseLang'];
    protected $beforeDelete  = [];
    protected $afterDelete    = [];
    
    
public function pickLang($data){
        // Can I modify the query here to alias column 'test_'.$_SESSION['lang'] AS test
    }
    public function parseLang($data){
        if(isset($data['data'])){
                $tmp false;
                if(isset($data['data']['id'])){
                    //only one row, add an additional dimension to array in prep foreach loop
                    $tmp['data'][0] = $data['data'];
                    $data $tmp;
                }
                
                
foreach($data['data'] as $key => $d) {
                    $test $d['test_'.$_SESSION['lang']];
                    unset($data['data'][$key]['test_en']);
                    unset($data['data'][$key]['test_es']);
                    $data['data'][$key]['test'] = $test;
                }
              
              
if($tmp){
                  //remove additional dimension if one was added
                  $data['data'] = $data['data'][0];
              }
              
          
}
          return $data;
    }

Adding variables passed by pagelinks

$
0
0
$pager->appends(['filter' => 'foo'])->links();
Is this a valid way to add data to pagelinks?

CRUD Code Generator

$
0
0
I know this is an off subject for many but thought I'd ask anyway.... I have a Scaffold/CRUD Gen that I have been working on specifically for myself. I started it a while back, found some that were cool and modeled after them a bit but it wasn't very modular and code updates kept breaking everything. The last one I found back in 2020 was good from Adel (https://github.com/Adel-Qusay/Codeignite...-generator) so I modeled mine over the years like this one. I just refreshed the code so it works great with PHP 8.2 and CI4 4.6. And, NO it is not a copy of Adels code aside from a few Token names Smile

Thoughts?
[Image: CI4-CRUD-Gen_2025-1.png]
[Image: CI4-CRUD-Gen_2025-2.png]
[Image: CI4-CRUD-Gen_2025-3.png]

Calendar Library for CodeIgniter4

$
0
0
I just adapted the fantastic original CI_Calendar Library (as in codeigniter 1.7.2), for PHP 8.*, tested with love on codeigniter 4.6

https://github.com/SergioDaroca/Calendar...deIgniter4

(to be honest DeepSeek did it all in one pass)
I have tested it -in codeigniter 4.6, and it works as the original did.

If somebody has the time to review, test, document, so it could be included in the framework, or set out as a module, it would be awesome.
This library was one of the main reasons I got to use CodeIgniter the first time. It is so easy and powerful.
I included a little howto, hope it helps! Smile

Debugbar not showing up

$
0
0
Hi,
i got this porject from a collegue who quit and did not leave and documentaiton on the project i tried using the debugbar to understand the code better but its not showing up at all even when doing all the configuraiton required this is the configuration and some reponse in the network tab from the browser
.htaccess
Code:
# Disable directory browsing
Options -Indexes

# ----------------------------------------------------------------------
# Rewrite engine
# ----------------------------------------------------------------------

# Turning on the rewrite engine is necessary for the following rules and features.
# FollowSymLinks must be enabled for this to work.
<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine On

# If you installed CodeIgniter in a subfolder, you will need to
# change the following line to match the subfolder you need.
# http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritebase
# RewriteBase /

# Redirect Trailing Slashes...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

#Add New Redirects Here

# Checks to see if the user is attempting to access a valid file,
# such as an image or css document, if this isn't true it sends the
# request to the front controller, index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]

# Ensure Authorization header is passed along
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

<IfModule !mod_rewrite.c>
# If we don't have mod_rewrite installed, all 404's
# can be sent to index.php, and everything works as normal.
ErrorDocument 404 index.php
</IfModule>

# Disable server signature start
ServerSignature Off
# Disable server signature end

<Files .env>
    Require all denied
</Files>

<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE image/svg+xml
    AddOutputFilterByType DEFLATE application/x-font
    AddOutputFilterByType DEFLATE application/x-font-truetype
    AddOutputFilterByType DEFLATE application/x-font-ttf
    AddOutputFilterByType DEFLATE application/x-font-otf
    AddOutputFilterByType DEFLATE application/x-font-woff
    AddOutputFilterByType DEFLATE application/x-font-woff2
    AddOutputFilterByType DEFLATE application/x-font-opentype
    AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
    AddOutputFilterByType DEFLATE application/font-woff
    AddOutputFilterByType DEFLATE application/font-woff2
    AddOutputFilterByType DEFLATE font/ttf
    AddOutputFilterByType DEFLATE font/otf
    AddOutputFilterByType DEFLATE font/eot
    AddOutputFilterByType DEFLATE font/woff
    AddOutputFilterByType DEFLATE font/woff2
    AddOutputFilterByType DEFLATE font/opentype
</IfModule>

<IfModule mod_expires.c>
  ExpiresActive On

# Images
  ExpiresByType image/jpeg "access plus 1 year"
  ExpiresByType image/gif "access plus 1 year"
  ExpiresByType image/png "access plus 1 year"
  ExpiresByType image/webp "access plus 1 year"
  ExpiresByType image/svg+xml "access plus 1 year"
  ExpiresByType image/x-icon "access plus 1 year"

  # Video
  ExpiresByType video/webm "access plus 1 year"
  ExpiresByType video/mp4 "access plus 1 year"
  ExpiresByType video/mpeg "access plus 1 year"

  # Fonts
  ExpiresByType font/ttf "access plus 1 year"
  ExpiresByType font/otf "access plus 1 year"
  ExpiresByType font/woff "access plus 1 year"
  ExpiresByType font/woff2 "access plus 1 year"
  ExpiresByType application/font-woff "access plus 1 year"

  # CSS, JavaScript
  ExpiresByType text/css "access plus 1 year"
  ExpiresByType text/javascript "access plus 1 year"
  ExpiresByType application/javascript "access plus 1 year"

  # Others
  ExpiresByType application/pdf "access plus 1 year"
  ExpiresByType image/vnd.microsoft.icon "access plus 1 year"
</IfModule>

PHP Code:
app/config/Filters.php

public array $aliases = [
        'csrf'          => CSRF::class,
        'toolbar'      => DebugToolbar::class,
        'honeypot'      => Honeypot::class,
        'invalidchars'  => InvalidChars::class,
        'secureheaders' => SecureHeaders::class,
        'cors'          => Cors::class,
        'forcehttps'    => ForceHTTPS::class,
        'pagecache'    => PageCache::class,
        'performance'  => PerformanceMetrics::class,
        'auth'          => \App\Filters\Auth::class,
    ];

    /**
    * List of special required filters.
    *
    * The filters listed here are special. They are applied before and after
    * other kinds of filters, and always applied even if a route does not exist.
    *
    * Filters set by default provide framework functionality. If removed,
    * those functions will no longer work.
    *
    * @see https://codeigniter.com/user_guide/incoming/filters.html#provided-filters
    *
    * @var array{before: list<string>, after: list<string>}
    */
    public array $required = [
        'before' => [
            'forcehttps'// Force Global Secure Requests
            //'pagecache',  // Web Page Caching
        ],
        'after' => [
            //'pagecache',  // Web Page Caching
            //'performance', // Performance Metrics
            'toolbar',    // Debug Toolbar
        ],
    ];

    /**
    * List of filter aliases that are always
    * applied before and after every request.
    *
    * @var array<string, array<string, array<string, string>>>|array<string, list<string>>
    */
    public array $globals = [
        'before' => [
            // 'honeypot',
            'csrf',
            // 'invalidchars',
        ],
        'after' => [
            // 'honeypot',
            // 'secureheaders',
        ],
    ]; 


.env
Code:
CI_ENVIRONMENT = development
#--------------------------------------------------------------------
# APP
#--------------------------------------------------------------------
app.baseURL = http://127.0.0.1/MDN3/
browser network tab
1/bootstrap.min.css 200 127.0.0.1 stylesheet
2/MDN3?debugbar_time=1744112539.451802 301 127.0.0.1 xhr / Redirect

how to manage DB connections

$
0
0
Hi If so how do  Team,
In my CI3 app I never worried about this because we autoloaded 'database' lib.
In CI4 it seems I now have to connect in my code - I have chosen the constructor of any Controller or Model where ever I need to access the database.
I am now aware that I could hit connection limits (currently 151 by default for mysql db)
A few (perhaps) obvious questions:
1) If I make a connection in a controller and the user session redirects to another controller will the $db persist for the session or do I open a second etc connection?
2) Should I check for an existing connection in each constructor and either proceed or open a new connection as appropriate? If so how please?
3) Another potential strategy would be to force a disconnect on completion of my db interation. If so how please?
4) I quite like the freeQuery() call. Is this recommended to optimise memory as lng as you don't need the cached result?
I have read the upgrade notes carefully but haven't found those nuggets yet.
Appreciate any thoughts and guidance.
TIA, Paul

Sorry typo in first line ...groan

Set session expiration time based on user role in CodeIgniter 4

$
0
0
Hi everyone,

I'm working with CodeIgniter 4 and I need to configure the session expiration time dynamically based on the user role at login.

I understand that, by default, CodeIgniter loads session settings from app/Config/Session.php, where the 'expiration' value is defined. However, this configuration is static and applied globally.

What I want to achieve is something like this:
  • If the user has the admin role, their session should last longer.
  • If the user has a standard role, the session should expire sooner.

I’m wondering if there’s a recommended way to override the session expiration time at runtime based on the user role. Is it possible to change the expiration after login, or would I need to implement a custom logic to handle expiration manually?

Any advice or example would be greatly appreciated.
Thanks in advance!

CodeIgniter Sandbox

hot to check if url exists

$
0
0
how to check if URL exists with codeigniter ?

I didn't find and try to do it with simple php but it is not as easy as I read. Maybe because php change and what works 10 years ago does not work today in 2025 with php 8 (I forget the decimal)
I try
curl_init($url))
  $headers = get_headers($url);
and differents easy solution but when I really check it it accept that it should not or I got php error message 
Do codeigniter have already done solution ?

I even try if ( file_get_contents($url, 'FILE_TEXT', NULL, 0, 1))

But I got this kind of error file_get_contents(): php_network_getaddresses: getaddrinfo for aaaaaaa failed: Temporary failure in name resolution
instead of true false
I try catch but always have erors impossible to say if I have any kind of error it is false

Command Line Tool

$
0
0
Executing the php spark command causes the message CodeIgniter v4.5.7 Command Line Tool - Server Time: 2025-04-14 18:46:24 UTC+02:00 to be displayed. Is there a way to disable this?

Proper use of migrations in a production project

$
0
0
Hello!

I've started working on a CI4 project that is already running for a while now and has a bunch of complex data and db structure but does not uses migrations.

As the documentation itself states: 
Quote:You could edit fragments of SQL by hand but you would then be responsible for telling other developers that they need to go and run them. You would also have to keep track of which changes need to be run against the production machines next time you deploy.

And those are exactly the problems we are having!

That being said, I wanted to know how exactly are you supposed to use migrations in production. Should I configure my deploys to run the command "php spark migrate" automatically? Is it safe? What do you recommend as the correct approach and steps to do it correctly and safely?
Viewing all 14343 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>