Hello,
I'm using CodeIngiter 4 and try to connect to a database.
I did these steps: 1) enter info in .env; 2) modified config/Database.php; 3) made a controller file to do/test the connection.
I received an error message. I experimented with .env, Database.php, and controller file in different ways. I wasn’t successful.
The error message points to “Constant expression contains invalid operations” in config/Database.php.
Here is section that defines data connection parameters in the .env file:
------------------------------------------------------------.env------------------------------------------------------
database.default.hostname = my_host_name
database.default.database = my_database_name
database.default.username = my_username
database.default.password = my_password
database.default.DBDriver = OCI8
database.default.DBPrefix =
database.default.port = my_port
------------------------------------------------------------------------------------------------------------------------
Here is the section that takes values from .env in config/Database.php:
------------------------------------------------------------config/Database.php-------------------------------------------
public $default = [
'DSN' => '',
'hostname' => env('database.default.hostname'),
'username' => env('database.default.username'),
'password' => env('database.default.password'),
'database' => env('database.default.database'),
'DBDriver' => env('database.default.DBDriver'),
'DBPrefix' => env('database.default.DBPrefix'),
'port' => env('database.default.port'),
'charset' => '',
'DBCollat' => '',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'numberNative' => false,
];
----------------------------------------------------------------------------------------------------------------
Here is the controller file.
-------------------------------------------------------------------------------------------------------
namespace App\Controllers;
use CodeIgniter\Controller;
use Config\Database;
class Getdata extends BaseController
{
public function index(): string
{
$db = \Config\Database::connect();
$query = $db->query('my_query');
$data = $query->getResult();
return view('getdata', $data);
}
}
<?
}
------------------------------------------------------------------------------------------------------------------------
The process never executed the controller file successfully. It stopped at the config/Database.php file. The config/Database.php needs to have the constant defined, before it actually calls the values. I read online. Do I need to define the constants in “__contruct” before using the values in config/Database.php?
Any help would be greatly appreciated!