How I will access a table from another Databse in cakephp - cakephp

I have two database in my project.
I have declared two connection variable in database.php. As follows:
var $development = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'xxxx',
'login' => 'xxxx',
'password' => 'xxxx',
'database' => 'yyyy',
'prefix' => '',
);
var $production = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'xxxxxx',
'login' => 'xx',
'password' => 'xx',
'database' => 'xxx',
'prefix' => '',
);
Now I am using the development as the default connection.
In one controller function I need to fetch some values from the anther DB. How can I get the other DB data there?
If any body can help regarding this I will very very obiliged to him/her.
Thank you in advance .

you can use $useDbConfig in your model class to define which database should it use for data source
class Example extends AppModel {
var $useDbConfig = 'development';
}
class Example extends AppModel {
var $useDbConfig = 'production';
}
and you can check the detail usage in cakephp document
http://book.cakephp.org/view/1057/Model-Attributes

Related

databse not configured error while insert record in laravel

I configured second database in laravel with name Test. but when i used to insert data in second database's table. It shows me an error, database not configured please help me to find where is my mistake?
I already make configuration to add new database in project. i changed .env file and database.php file in config folder. but nothing can help me.
database.php
'mysql2' => [
'driver' => 'mysql',
'host' => 'localhost',
'port' => '3306',
'database' => 'Test',
'username' => 'root',
'password' => '',
'unix_socket' => '',
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
.env
DB_CONNECTION_SECOND=mysql2
DB_HOST_SECOND=127.0.0.1
DB_PORT_SECOND=3306
DB_DATABASE_SECOND=Test
DB_USERNAME_SECOND=root
DB_PASSWORD_SECOND=
SellerSelectProduct.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class SellerSelectProduct extends Model
{
protected $connection = 'Test';
protected $fillable = ['product_id'];
public function product(){
return $this->belongsTo(Product::class);
}
}
SellerBaseController.php
<?php
namespace App\Http\Controllers;
use App\Category;
use Illuminate\Http\Request;
use App\SellerSelectProduct;
class SellerBaseController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function someMethod()
{
$someModel = new SellerSelectProduct;
$someModel->setConnection('Test');
$something = $someModel->find(1);
return $something;
}
}
SellerProductController.php
<?php
namespace App\Http\Controllers;
use App\City;
use App\State;
use Illuminate\Http\Request;
use App\SellerSelectProduct;
class SellerProductController extends SellerBaseController
{
public function someMethod()
{
$someModel = new SellerSelectProduct;
$someModel->setConnection('Test');
$something = $someModel->find(1);
return $something;
}
public function index(State $state)
{
return $state->Cities;
}
public function addproducts(Request $request){
SellerSelectProduct::insert($request->data);
return response()->json([
'message' => 'Selected product list updated successfully'
]);
}
}
a sample of a second conection.
.env
DB_CONNECTION=mysql2
DB_HOST2=127.0.0.1
DB_PORT2=3306
DB_DATABASE2=
DB_USERNAME2=
DB_PASSWORD2=
database.php
'mysql2' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST2', ''),
'port' => env('DB_PORT2', '3306'),
'database' => env('DB_DATABASE2', 'forge'),
'username' => env('DB_USERNAME2', 'forge'),
'password' => env('DB_PASSWORD2', ''),
'unix_socket' => env('DB_SOCKET2', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
To have an effect on clean or cache changes with or optimize handmade php command.

Connect multiple database in one controller cakephp 2

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

Cakephp delete not working for multiple DB connect

I am using cakephp 2.4 , am working on a project which uses two db connections based on the user logged in. while accessing the second DB and Retrieve data it is working fine, but when i delete record in the second DB table record its throw error as ..
Invalid catalog name: 1046 No database selected
Can anyone help on this ...
this is my DB connect code
$this->default['host'] = 'localhost';
$this->default['login'] = 'xxxxxx';
$this->default['password'] = 'xxxx';
$this->default['database'] = 'xxxxx';
$this->default['prefix'] = 'xxxx_';
if(!empty($_SESSION['subsites'])){
$this->test['host'] = 'localhost';
$this->test['login'] = 'xxxx';
$this->test['password'] = 'xxxxx';
$this->test['database'] = 'ccxxxx';
$this->test['prefix'] = 'xxxx'.'_';
}
then we used $useDBconfig ='test'; in model
Define multiple database configuration in app/config/database.php as
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => '',
'database' => 'db1',
'prefix' => '',
//'encoding' => 'utf8',
);
public $subSites = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => '',
'database' => 'db2',
'prefix' => '',
//'encoding' => 'utf8',
);
Now when you want to switch to subSites config just write following code:
$this->Model->useDbConfig = $subSites;
You can use $useDbConfig Attribute inside your Model.
class Example extends AppModel {
public $useDbConfig = 'user';
}
Inside your Controller, simply use:
$this->ModelName->useDbConfig = 'user';
for More Details, please click on http://book.cakephp.org/2.0/en/models/model-attributes.html

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