Connect multiple database in one controller cakephp 2 - cakephp-2.0

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',
);

Related

how to manage database in laravel

i want to use multiple databases, i have 1db/user and 1 main db,already set main db in config file but how to manage user database(db name = {user_id}_db). thanks in advance
this is my config code
'main' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
You can use following configuration for multiple dbs.
<?php
return array(
'default' => 'mysql',
'connections' => array(
# primary
'mysql' => array(
'driver' => 'mysql',
'host' => 'ip1',
'database' => 'db1',
'username' => 'user',
'password' => 'pwd'
'charset' => 'utf8',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
),
# secondary db connection
'mysql2' => array(
'driver' => 'mysql',
'host' => 'dbip2',
'database' => 'db2',
'username' => 'user',
'password' => 'pwd'
'charset' => 'utf8',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null
),
'sqlite' => array(
'driver' => 'sqlite',
'database' => __DIR__.'/../database/db.sqlite',
'prefix' => '',
),
),
);
Then you can use the the connection() method:
$connection = ‘mysql2’;
Schema::connection($connection)->create(function(Blueprint $table) {
//
});
Creating DB for each user is useless, even if you are doing it for security or any other purpose whatsoever. Useful SO link MySQL performance: multiple tables vs. index on single table and partitions
Your question (connecting to multiple databases in Laravel) is already answered here. How to use multiple database in Laravel
UPDATE
I guess, you want to create new databases on the fly and connect to them (without using .env configuration). Create dynamic connections instead of specifying 'connection-name' when trying to connect to a new database. Then, using Config::set you can create new temporary connections and then use DB::connection with the temporary name you just created. read more https://lukevers.com/2015/03/25/on-the-fly-database-connections-with-laravel-5

Call Config::set to change database in Lumen 5.4? (Using Eloquent)

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.

change default db in cakephp3

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.

Cakephp How to change database connection

I have 2 controllers, ContentController for general user and ManageController for administrator. I need to change the connection from default to admin and I have this code in my database.php
class DATABASE_CONFIG {
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'user',
'password' => '',
'database' => 'ComputerScience',
'prefix' => '',
'encoding' => 'utf8',
);
public $admin = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'admin',
'password' => '',
'database' => 'ComputerScience',
'prefix' => '',
'encoding' => 'utf8',
);
}
Thank you
So, inside your Model, you would use the useDbConfig Attribute:
class Example extends AppModel {
public $useDbConfig = 'admin';
}
Inside your Controller, simply use:
$this->ModelName->useDbConfig = 'admin';
Thats all.
I would use Model::setDataSource() rather than just setting the database config var. This is because there are other possible changes that come with changing the datasource:
$this->Model->setDataSource('admin');

Variable database setting Cakephp

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");

Resources