I have a small application in Lumen which should handle multiple databases based on the request URL. To make this possible in the first place I've created a folder /config/ and a config-file called /config/database.php. Here is the code and I added some comments to show what I exactly need to do.
<?php
return [
'migrations' => 'home',
'default' => 'home',
'connections' => [
// This is the default option and its needed to check if the "client" exists.
'home' => [
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'home',
'username' => 'root',
'password' => 'password',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
// When the client is found in the "home" connection, I'd like to continue with this database settings as default.
'client' => [
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'client_', // There is one database per client which in the end will look like this: "client_******", so I have to add this using Config:set...
'username' => 'root',
'password' => 'password',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
],
];
I have to call Config::set to change these settings but it doesnt seem to be available on Lumen. How can i change these settings (the default database connection and its database)
I hope there is a way to make this possible. Thanks a lot :)
I found the solution.
To set and edit your configuration use the "config" helper method with an array as argument.
Example:
config(['database.default' => 'your_connection']);
In a query you can use as follows:
$connectionClient = DB::connections('client');
$connectionHome = DB::connections('home');
I hope have helped.
Related
I need for my drupal 8 installation to connect a second database for a view.
I install the module views_database_connector (january 2015 release)
I connect with the setting.
but nothing works, i don't see my database with view.
my settings...
$databases['default']['default'] = array (
'database' => 'first base',
'username' => 'first base',
'password' => 'xxxxx',
'prefix' => '',
'host' => 'localhost',
'port' => '3306',
'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
'driver' => 'mysql',
);
$databases['external']['default'] = array (
'database' => 'second_base',
'username' => 'second_base',
'password' => 'yyyyyy',
'prefix' => '',
'host' => 'localhost',
'port' => '3306',
'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
'driver' => 'mysql',
);
Does this module need a patch, and how to apply ??
For this you can create multiple database connection in setting file :
use \Drupal\Core\Database\Database::setActiveConnection('external'); to get current active connection.
In a controller I want to change the default database so i can access the new db (db2) from anywhere in the website. The db2 database has the same models but just different data. My code just accesses the other database but doesnt set the new default database to db2 which can be accessed anywhere in the website. I didnt get the answer from the below posts.
This is my controller :
$connection = ConnectionManager::get('db2'); // 'db2' where my second database is configured
$results = $connection->execute('SELECT * FROM tutors')->fetchAll('assoc');
//this works but doesnt set the default database to db2 everywhere
This is my app.php :
'Datasources' => [
'default' => [
'className' => 'Cake\Database\Connection',
'driver' => 'Cake\Database\Driver\Mysql',
'persistent' => false,
'host' => 'localhost',
//'port' => 'non_standard_port_number',
'username' => 'root',
'password' => '',
'database' => 'aptutori_test',
'encoding' => 'utf8',
'timezone' => '+11:00',
'flags' => [],
'cacheMetadata' => true,
'log' => false,
'quoteIdentifiers' => false,
'url' => env('DATABASE_URL', null),
],
'db2' => [
'className' => 'Cake\Database\Connection',
'driver' => 'Cake\Database\Driver\Mysql',
'persistent' => false,
'host' => 'localhost',
//'port' => 'non_standard_port_number',
'username' => 'root',
'password' => '',
'database' => 'aptutori_testbak',
'encoding' => 'utf8',
'timezone' => '+11:00',
'flags' => [],
'cacheMetadata' => true,
'log' => false,
'quoteIdentifiers' => false,
'url' => env('DATABASE_URL', null),
],
Dynamically change database connection in cakephp 3
http://mark-story.com/posts/view/using-cakephp-and-a-horizontally-sharded-database
Use ConnectionManager::alias():
http://api.cakephp.org/3.0/class-Cake.Datasource.ConnectionManager.html#_alias
Fore example this will make all tables that require the default connection to use db2:
ConnectionManager::alias('db2', 'default');
You could do this application wide in a Middleware in > cake 3.3, opposed to using a DispatcherFilter, like described in http://mark-story.com/posts/view/using-cakephp-and-a-horizontally-sharded-database.
<?php
namespace App\Middleware;
use Cake\Datasource\ConnectionManager;
class TenantShardMiddleware
{
public function __invoke($request, $response, $next)
{
$tenant = $request->getHeader('MY-tenant');
ConnectionManager::alias($tenant[0], 'default');
$response = $next($request, $response);
return $response;
}
}
In my example above I'm using a special Request Header to switch databases.
(Laravel Config::set Persist Through Requests?)
After getting the answer below, I tried it out...
'default' => 'mysql_main',
'connections' => [
'mysql_main' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],
'mysql_company' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '3306'),
'database' => Auth::user()->club->db_name,
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],
],
However, upon doing this inside the database.php folder under config I receive the following error...
Fatal error: Class 'Auth' not found in F:\trapstats_v5\config\database.php on line 73.
Is there another way to do dynamic database connections, based on the user, that will save through requests instead of doing config([database.connections.mysql_company.database' => Auth::user()->club->db_name]) every time I want to access the dynamic connection?
This question is similar to the answer of Dynamic database connection in Laravel. And if I do this answer as well I get the same sort of error except this time it is called Session instead of Auth.
In your config files doing
'database' => Auth::user()->club->db_name,
Is dangerous because Auth is probably not setup at the point your configuration files are read by Laravel, it needs your configuration files to lots of other things, so it should read them fist. What you can do, in, lets say a ServiceProvider, or some other helper class is to:
config('database.connections.mysql_company', ['database' => Auth::user()->club->db_name]);
After doing some more reading and going around and asking many questions I have come up with a solution.
What I ended up doing was creating a middleware called Database that ran AFTER every other middleware finished. This allowed for use of all of the typical Laravel services (like Auth::user());
Database
class Database
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (!Auth::guest()) {
config(['database.connections.club.database' => Auth::user()->club->db_name]);
}
return $next($request);
}
}
And then for the route group I assign this middleware to it.
Hello I am new to cakephp 2. I want to know, how to connect to database in one controller and loop for each. Please help me with details.
I have already set the following in the database config:
class DATABASE_CONFIG {
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => '',
'database' => 'db_one',
'prefix' => '',
//'encoding' => 'utf8',
);
public $database2 = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => '',
'database' => 'db_announcement',
'prefix' => '',
//'encoding' => 'utf8',
);
You should research bit more in google before asking question here.
Anyways, CakePHP takes default database connection which is there in database.php in core folder, so all your queries which you execute in the database which is defined in default vairable in database.php and if you want to connect multiple database than you can try something like this.
In your database configuration file:
public $database2 = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => '*******',
'database' => '*****',
'prefix' => '',
'encoding' => 'utf8',
);
And in your controller you can have connection in this way:
$db = ConnectionManager::getDataSource('user');
$list = $db->rawQuery('your query'); or customized CakePHP queries can work here too
I hope you will get your answer from this.
Thanks
$i=0;
$total=$list->fetchAll(PDO::FETCH_ASSOC);
instead of getDataSource method I would suggest to use $this->ModelName->setDataSource('mongo');
E.g If you want to fetch the data from User model of 'mongo' database source , which you have mentioned in database.php, then to set that it would look like.
$this->User->setDataSource('mongo')
in database.php you are having following code
public $mongo = array(
'datasource' => 'Mongodb.MongodbSource',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => 'root',
'database' => 'mongo_data',
'prefix' => '',
'encoding' => 'utf8',
);
I'm searching a way to create a variable database in Cakephp.
I'm creating a website in wich the database setting (user, pass, db) depends of the user who logg's in. The database settings come from another database.
Thanks in advance,
AƤron
-- ANSWER
Thanks for your quick reply.
I know how to switch between databases, but the database settings have to be variable.
Example
$db = $this->DB_SET['DB_SET']['db']; //from model DB_SET the database
$db_login= $this->DB_SET['DB_SET']['login'];
$db_host= $this->DB_SET['DB_SET']['host'];
$db_pass= $this->DB_SET['DB_SET']['pass'];
var $db2 = array(
'driver' => 'mysql',
'persistent' => false,
'host' => $db_host,
'login' => $db_login,
'password' => $db_pass,
'database' => $db,
'prefix' => '',
'encoding' => 'UTF8',
'port' => '',
);
If you're looking to create database connections on the fly, you may want to use ConnectionManager::create().
// get logged in user's id and create a connection for them
$id = $this->Auth->user('id');
ConnectionManager::create("user_$id_db", array(
'driver' => 'mysql',
'persistent' => false,
'host' => $db_host,
'login' => $db_login,
'password' => $db_pass,
'database' => $db,
'prefix' => '',
'encoding' => 'UTF8',
'port' => '',
));
Then set your models to use it when you're ready.
// get logged in user's id and use their connection
$id = $this->Auth->user('id');
$this->Model->setDataSource("user_$id_db");