1
votes

In SilverStripe how can I save data to an external database table, which has not been created by SilverStripe?

For example: I have created a News table and want - if I add new a News item - that the same data is stored in my previous News table.

2
Why do you want to store the News data in another table? I would not recommend duplicating the data across two tables. I would instead suggest using the SilverStripe News table data for everything. Is that a possible solution for you? - 3dgoo

2 Answers

0
votes

If the tables are the same you can actually just switch the database config and then use the ORM and then switch is back...

$otherDB = array(
    "type"      => 'MySQLDatabase',
    "server"    => 'localhost',
    "username"  => 'new_user',
    "password"  => 'xxxx',
    "path"      => '',
    "database"  => 'new_database'
);

DB::connect($otherDB);
//Use ORM to write

//revert to normal credentials
global $databaseConfig;
DB::connect($databaseConfig);
3
votes

I would create a restful API to keep things separate, so you don't need to keep the external db credentials in your SilverStripe site.

You can use https://github.com/guzzle/guzzle to POST the News to the external site (where the external db lives) from your SilverStripe site (onAfterWrite) for example. On the external site you'll need to create a simple API server that listens to Post requests and if valid saves them in the db. What out for sql injections!

hope it helps.