@deron
In CakePHP, you can define a database connection in the app/config/database.php file. Here's an example configuration for a MySQL database:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class DATABASE_CONFIG { public $default = array( 'datasource' => 'Database/Mysql', 'persistent' => false, 'host' => 'localhost', 'login' => 'your_username', 'password' => 'your_password', 'database' => 'your_database', 'prefix' => '', 'encoding' => 'utf8' ); } |
This configuration defines a connection named default that uses the Database/Mysql datasource to connect to a MySQL database running on localhost. The login and password properties should be set to the username and password for your database user, and the database property should be set to the name of the database you want to connect to.
You can define additional connections by adding more properties to the DATABASE_CONFIG class. For example, if you wanted to define a connection to a PostgreSQL database, you could add the following configuration:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
class DATABASE_CONFIG { public $default = array( 'datasource' => 'Database/Mysql', 'persistent' => false, 'host' => 'localhost', 'login' => 'your_username', 'password' => 'your_password', 'database' => 'your_database', 'prefix' => '', 'encoding' => 'utf8' ); public $pgsql = array( 'datasource' => 'Database/Postgres', 'persistent' => false, 'host' => 'localhost', 'login' => 'your_username', 'password' => 'your_password', 'database' => 'your_database', 'prefix' => '', 'encoding' => 'utf8' ); } |
In this example, the configuration defines a connection named pgsql that uses the Database/Postgres datasource to connect to a PostgreSQL database running on localhost.
@deron
In CakePHP, you can define a database connection by configuring your database credentials in the app.php file, located in the config directory. Here are the steps to follow:
Here's an example configuration for a MySQL database connection:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// config/app.php // ... 'Datasources' => [ 'my_db_connection' => [ 'className' => 'CakeDatabaseConnection', 'driver' => 'CakeDatabaseDriverMysql', 'host' => 'localhost', 'username' => 'my_user', 'password' => 'my_password', 'database' => 'my_database', 'timezone' => 'UTC', ], ], // ... |
You can then use this database connection by referencing its name in your application code, for example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// src/Model/Table/UsersTable.php namespace AppModelTable; use CakeORMTable; class UsersTable extends Table { public function initialize(array $config): void { parent::initialize($config); $this->setTable('users'); $this->setConnection('my_db_connection'); // use the 'my_db_connection' database } } |
Note that you can define multiple database connections in the app.php file, each with a unique name and configuration.