CodeIgniter4: Bug: Inserting data using multiple databases uses default connection

PHP Version

7.3

CodeIgniter4 Version

4.1.8

CodeIgniter4 Installation Method

Composer (using codeigniter4/appstarter)

Which operating systems have you tested for this bug?

macOS

Which server did you use?

cli-server (PHP built-in webserver)

Database

MySql 8.0

What happened?

I’m trying to use multiple database connections for an API.

default - this DB connection will access the API authorization details dbother - this DB handles the get,post,put API request

when I try to use post request and insert data to dbother its shows error that its still accessing the default db. however, using get and update does work and I can access the dbother connection. Only the post has issue and still redirecting to the default db connection

Steps to Reproduce

create two db connection:

  1. default - created in .env and database.php port 3306
  2. dbother - created in .env and database.php por: 33060 (this is a remote database)

use post method by inserting data to dbother connection

Expected Output

A success message from my API and check if it’s stored in the dbother connection.

Anything else?

title": “mysqli_sql_exception”, “type”: “mysqli_sql_exception”, “code”: 500, “message”: “Table ‘dbother.users’ doesn’t exist”, “file”: “/Users/barneycruzv/Desktop/web_dev/cda_api/vendor/codeigniter4/framework/system/Database/MySQLi/Connection.php”, “line”: 292, “trace”: [ { “file”: "/

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 15 (9 by maintainers)

Most upvoted comments

This is not a bug. You don’t specify DB group to your Validation object, so the default group is used.

Add the following in the controller:

protected function validate($rules, array $messages = []): bool
    {
        $this->validator = Services::validation();

        // If you replace the $rules array with the name of the group
        if (is_string($rules)) {
            $validation = config('Validation');

            // If the rule wasn't found in the \Config\Validation, we
            // should throw an exception so the developer can find it.
            if (! isset($validation->{$rules})) {
                throw ValidationException::forRuleNotFound($rules);
            }

            // If no error message is defined, use the error message in the Config\Validation file
            if (! $messages) {
                $errorName = $rules . '_errors';
                $messages  = $validation->{$errorName} ?? [];
            }

            $rules = $validation->{$rules};
        }

        return $this->validator->withRequest($this->request)->setRules($rules, $messages)->run(null, null, 'otherDB');
    }

Aha! You don’t use in Model validation. You are using Validation object in the controller. It uses the default DB group. So you can’t validate well.