How to save the data into two databases in CakePHP - php

In my app/Config/database.php I have a setup which looks like this,
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => '',
'database' => 'default_db',
'prefix' => '',
//'encoding' => 'utf8',
);
public $second = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => '',
'database' => 'second_db',
'prefix' => '',
//'encoding' => 'utf8',
);
Now what I wanted was to simultaneously save the data, wherever and whenever I am saving any kind of data. This databases are identical, that is why I want to save the data to both databases to maintain them being identical. Where would I edit such that all the save/edit/update/delete processes will both save to both databases. Thank you in advance.
EDIT
in my lib/Cake/Model/Model.php is a line of code which looks like this
/**
* The name of the DataSource connection that this Model uses
*
* The value must be an attribute name that you defined in `app/Config/database.php`
* or created using `ConnectionManager::create()`.
*
* #var string
* #link http://book.cakephp.org/2.0/en/models/model-attributes.html#usedbconfig
*/
public $useDbConfig = 'default';
is there where I should start editing to be able to save the data into two databases? Thanks.

Doing this through CakePHP is slow and not necessary, why aren't you using a feature like DB replication? However, you can change the connection the model us using through the model property useDbConfig.
$this->save($data);
$this->useDbConfig = 'second';
$this->save($data, array('callbacks' => false, 'validate' => false);
$this->useDbConfig = 'default';
You could add the last three lines of the above code to your Model::afterSave() callback, or much better, do it via a behavior and attach it to each model that needs it.

Related

Syntax error or access violation at the time of cake bake in cakephp

How can I solve this error?
At the time of cake bake.
This is my database configuration:
class DATABASE_CONFIG {
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => '',
'database' => 'cakephp2.9',
'prefix' => '',
//'encoding' => 'utf8',
);
}
This is my database configuration class DATABASE_CONFIG { public $default = array( 'datasource' => 'Database/Mysql', 'persistent' => false, 'host' => 'localhost', 'login' => 'root', 'password' => '', 'database' => 'cakephp2.9', 'prefix' => '', //'encoding' => 'utf8', ); }
CakePHP currently doesn't support database names with dots, as the routine that handles quoting names is being used for column names as well, in which dots are treated as separators for aliases and columns, ie for stuff like TableAlias.column_name, which is being converted to `TableAlias`.`column_name`, causing your database name to make it into the query as `cakephp2`.`9` which will of course fail.
Long story short, rename your database.

How do I automatically login to another database from a current website in cakephp

In cakephp I login in to the mysql database no problem. I have an issue where once I login I need to access another database(button click) on the same server on another cakephp website. I dont want the user to login again on the other website. I cant find information on solving this problem . How do I automatically login to another cakephp website?
To be clearer about what I want is that I want the user to login and then click a button and use another cakephp website with a different database without having to login. Setdatasource seems to be staying in the same cakephp website and switching databases
The following code works fine (on my pc) but I I need to automatically login to the website without having to login again
echo $this->Html->link( 'link!', 'http://127.0.0.1/maths/numeracyStudents/dashboardst');
public $mathdb = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => '127.0.0.1',
'login' => 'root',
'password' => '',
'database' => 'maths',
'prefix' => '',
//'encoding' => 'utf8',
);
//called this function from the controller and nothing happens?
public function changedb() {
$this->NumeracyStudents->setDataSource('mathdb');
}
Inside your application's app.php,you would create another database configuration like the default one and label it. Then, you will use that config to create a connection.
EDIT: I am assuming you are using CakePHP 2.X
database.php
class DATABASE_CONFIG {
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'cakephpuser',
'password' => 'c4k3roxx!',
'database' => 'my_cakephp_project',
'prefix' => ''
);
public $otherDb = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'cakephpuser',
'password' => 'c4k3roxx!',
'database' => 'my_cakephp_project2',
'prefix' => ''**strong text**
);
}
ArticlesController:
//inside a function(action) you would call this to set to the other datasource
$this->Articles->setDataSource('otherDb');

DB::raw() always uses default database

I've been searching for a while for a solution here but no luck. I have a model named Currency which extends eloquent.
class Currency extends Eloquent {
protected $connection = 'currency';
protected $table = 'dbo.sfCXDetail';
public $timestamps = false;
public function monthlyTransactions(){
return Currency::select(array(DB::raw('COUNT(trx_number) AS Transactions'), DB::raw('MONTH(update_stamp) as TransactionsMonth')))
->whereBetween(DB::raw('DATEPART(YYYY, update_stamp)'), array(2012,2012))
->groupBy(DB::raw('YEAR(update_stamp)'))
->groupBy(DB::raw('MONTH(update_stamp)'))
->orderBy(DB::raw('YEAR(update_stamp)'))
->orderBy(DB::raw('MONTH(update_stamp)'))
->get();
}
}
The problem is, DB::raw uses the default database inside the database config file, so when I try using:
Currency::raw()
I get an error
strtolower() expects parameter 1 to be string, object given
The database I'm using can't be used as the default database. How do I use the DB::raw method with the current database in use inside the model?
This query works without error when I set the default database to 'currency', but not if I set it to use my local default mysql database.
This is in my DB config file:
'currency' => array(
'driver' => 'sqlsrv',
'host' => 'xx',
'database' => 'xx',
'username' => 'xx',
'password' => 'xx',
'prefix' => '',
),
You can try something like this:
DB::connection('specialConnection')->raw(...);
Also, you have to add another config settings for that connection like:
'currency' => array(
'driver' => 'sqlsrv',
'host' => 'xx',
'database' => 'xx',
'username' => 'xx',
'password' => 'xx',
'prefix' => '',
),
'specialConnection' => array(
'driver' => 'mySql',
'host' => 'xxx',
'database' => 'xxx',
'username' => 'xxx',
'password' => 'xxx',
'prefix' => '',
)
I could be wrong but I believe that setting the connection property as a protected property of Currency would not also set connection for the DB class.
would something like this work (I am at work at not able to test, sorry):
$db = new DB;
$db->connection = 'currency'
$db->table = 'dbo.sfCXDetail';
...
return Currency::select(array($db->raw('COUNT(trx_number) ...
...
I think it's a scope thing

error with using variables as associative array value in php

For some reason this is giving me the follow error: syntax error, unexpected T_VARIABLE:
$mysql = json_decode(getenv("VCAP_SERVICES"));
$mysql = $mysql["mysql-5.1"][0]["credentials"];
class DATABASE_CONFIG {
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'port' => $mysql['port'], // <-- Line with error
'login' => $mysql['username'],
'password' => $mysql['password'],
'database' => $mysql['name'],
'prefix' => ''
//'encoding' => 'utf8',
);
public $test = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'user',
'password' => 'password',
'database' => 'test_database_name',
'prefix' => '',
//'encoding' => 'utf8',
);
}
I know you can use variables as values in arrays, so what is going on?
It looks like you're trying to set the default value of a property to a variable.
You can't do that, not even inside an array. This is half PHP's parser sucking, a quarter of PHP's lack of appropriate error message, and a bit of sanity.
You'll need to do it from within the constructor instead by passing in $mysql:
$config = new DATABASE_CONFIG($mysql);
class DATABASE_CONFIG {
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'port' => null,
'login' => null,
'password' => null,
'database' => null,
'prefix' => ''
//'encoding' => 'utf8',
);
public function __construct($mysql) {
$this->default['port'] = $mysql['port']; // etc
}
}
$mysql has no scope inside the class.
You need to inject it as an argument into the class constructor, and then define your array values for the class properties
You're trying to reference a variable inside a class which is defined outside of that class.
PHP has no idea what $mysql is inside of that class definition.

How to config cakephp 2.2 database connection with appfog service

I'have some problem to config cakephp database connection with appfog service.
AppFog provides JSON database config by VCAP_SERVICES variable like this
{
"mysql-5.1" = (
{
credentials = {
host = "ap01-user01.c0ye1hvnkw6z.ap-southeast-1.rds.amazonaws.com";
hostname = "ap01-user01.c0ye1hvnkw6z.ap-southeast-1.rds.amazonaws.com";
name = ?????????????;
password = ????;
port = 3306;
user = ?????;
username = ???????????;
};
label = "mysql-5.1";
name = "???????-mysql-56200";
plan = free;
tags = (
mysql,
"mysql-5.1",
relational
);
}
); }
In cakephp database config file like this
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => $mysql_config["hostname"],
'login' => $mysql_config["username"],
'password' => $mysql_config["password"],
'database' => $mysql_config["name"],
'prefix' => '',
//'encoding' => 'utf8',
);
How to fix this problem?
You will want to parse the json into an array (if you only have ONE mysql db bound to the app, if you have more you will need to change the "0" to another number to reflect the second bound mysql service):
$services = getenv("VCAP_SERVICES");
$services_json = json_decode($services,true);
$mysql_config = $services_json["mysql-5.1"][0]["credentials"];
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => $mysql_config["hostname"],
'login' => $mysql_config["user"],
'password' => $mysql_config["password"],
'database' => $mysql_config["name"],
'port' => $mysql_config["port"],
'prefix' => '',
//'encoding' => 'utf8',
);
The above changes "username" to "user" and basically follows the premise of what appfog does with Wordpress: https://github.com/appfog/af-php-wordpress/blob/master/wp-config.php

Categories