Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cakephp - Connect to different database/host from inside an action

Tags:

mysql

cakephp

In cakephp I want to be able connect to a different database from one action on the site. The action determines which database and host to connect to. Using cakephp 1.3.

Ive seen where you can change the db connection in beforeFilter for a controller, but I want to be able handle this from the action, because that is where I find the database and/or host, that I need to connect to.

I can write my own SQL inside there. I don't need to go through models. Just want to do a simple add/update SQL statement.

like image 842
madphp Avatar asked Apr 09 '26 08:04

madphp


1 Answers

You can easily configure more than one database connection to use in your app.

In config/database.php, create another variable for your database configuration, in addition to the existing $default:

var $otherDatabase = array(
    'driver' => 'mysql',
    // more settings...
);

Then, in your model, set $this->useDbConfig = 'otherDatabase' or in your controller $this->MyModel->useDbConfig = 'otherDatabase'. Any subsequent find()s will use the configured database.

like image 194
pixelistik Avatar answered Apr 10 '26 21:04

pixelistik