Change active database in doctrine - php

Using Doctrine, I need to run "SHOW DATABASES" and for each database perform some sanity checks.
What I did is:
$config = new \Doctrine\DBAL\Configuration();
$connectionParams = array('url' => $DB_URL, );
$conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config);
$conn->prepare("SHOW DATABASES")
....
Now that I have the list of DB's, how can issue the Doctrine's equivalent of USE my_db ? So that further SQL's are executed on that database?

It depends on a database management system you use. In common case you should create a new connection if you want to use a new database.
Database is a part of connection params you give to a \Doctrine\DBAL\DriverManager to get a connection. (http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html)

Related

Is there any way to connect to multiple dynamic databases in controller side using cakephp 3.7?

We are using a connection manager to do the process but we are unable to achieve the thing that we needed. we tried different ways to unable to connect to dynamic multiple databases. below is the code which we are using.
php 5.6 above with cakephp 3.7 versions.
use Cake\Controller\Component;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
use Cake\Database\Connection;
use Cake\Database\Driver\Mysql;
public function setDatabase($company_id, $datasource = 'default') {
$dbConf = ConnectionManager::getConfig($datasource); //Here connect to dynamic database.
$dbConf['database'] = "db_".$company_id;//changing database name to which we need to connect with same configurations
$dbConf['name'] = "company";
$dbConf['encoding'] = 'utf8';
ConnectionManager::setConfig('company', $dbConf );
// ConnectionManager::config('company', $dbConf );
$JobSeekers = TableRegistry::get('JobSeekers');
$JobSeekers_details = $JobSeekers->find('all'); // firing query jobseekers table but still it's excueting in default db instead of company db.which trows error
$JobSeekers_data = $JobSeekers_details->first();
pr($JobSeekers_data);
}
What we need is jobseeker query must be execute in company level database but we are getting following error which says connection still in default db.
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'default_db.job_seekers' doesn't exist

Change the Database Connection Dynamically in Laravel [duplicate]

This question already has answers here:
Laravel: connect to databases dynamically
(8 answers)
Closed 3 years ago.
I have the master database with login table and corresponding database settings for each user. On login I should dynamically change the db settings fetching from the table.
I can change the db connection but this is not persisting.
Config::set("database.connections.mysql", [
'driver' => 'mysql',
"host" => $usr_host,
"database" => $usr_database,
"username" => $usr_username,
"password" => $usr_password,
...
]);
edit:
New database is created for each user when he/she registers with the app and thus i dont have the database connection for each user defined in the config/database.php
This way you can set new parameter when it comes to database:
\Config::set('database.connections.mysql.database', $schemaName);
Remember about PURGE to persist this settings
DB::purge('mysql');
Cheers!
Well you can use the default database for user login and have a new field for the database name. Then whenever you need to query a different database, you can just change your db connection.
Something like this
$someModel = new SomeModel;
$databaseName = "mysql2"; // Dynamically get this value from db
$someModel->setConnection($databaseName);
$something = $someModel->find(1);
You can read more about it here.
http://fideloper.com/laravel-multiple-database-connections
you need to get the config first.. then alter the specific field then set it back..
$config = Config::get('database.connections.company');
$config['database'] = "company_tenant_$id";
$config['password'] = "test2123";
config()->set('database.connections.company', $config);
I think a good place to change the database connection place is in bootstrap/app.php file, use the code below:
$app->afterBootstrapping(\Illuminate\Foundation\Bootstrap\LoadConfiguration::class, function ($ap) {
// your database connection change may happens here
});
It is before ServiceProvider register and boot, so even if you use DB or Eloquent staff in ServiceProvider, it works very well.
In laravel what you can do is create the different connections in the connections array of the file conf/database, then these connections you can use them when you are going to carry out operations in your application.
If you use query builder or raw expresions you must use the connection ('name') method to perform queries, for example:
$users = DB::connection('mysql')
->table('users')
->select(...)
->get();
If you use eloquent you can specify the name of the connection in the model file in the connection attribute, for example:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The connection name for the model.
*
* #var string
*/
protected $connection = 'mysql';
}
A solution to your problem could be that you have created the different types of connections according to the users in the file conf/database, and save the name of the connection that the user uses as a column in the user table, and when you go to make the queries you get the name of the connection of the user, for example:
$user = User::find(Auth::id());
$connection = $user->connection;
$users = DB::connection($connection)
                      ->table('users')
                      ->select(...)
                      ->get ();
more info:
https://laravel.com/docs/5.5/eloquent#eloquent-model-conventions
https://laravel.com/docs/5.5/database#read-and-write-connections
After an extensive search I found it this way:
Go to this file vendor\laravel\framework\src\Illuminate\Auth\Middleware\Authenticate.php
Go to the method: protected function authenticate($request, array $guards)
and right after the method has started, paste the following code:
if(auth()->check() && !empty( auth()->user()->db_name )){
$dynamic_db_name = auth()->user()->db_name;
$config = \Config::get('database.connections.mysql');
$config['database'] = $dynamic_db_name;
$config['password'] = "Your DB Password";
config()->set('database.connections.mysql', $config);
\DB::purge('mysql');
}
first we are checking if the user is logged in with
auth()->check()
Then as you may have added db_name name or the like column table to your users table according to each user. So in the next condition, I am making sure that the db_name is available:
&& !empty( auth()->user()->db_name )
Then after execution enters the if condition I get the db_name from the user record and set the configuration according to the user database, save the config and use purge method of DB class to persist this setting.
I was really stuck with it. I did not wanted to change my db connection in every class. So this is how I got it. Now I can use both Eloquent and DB without any tension anywhere. In my application I have one centeral database for login of all users and then for each organization there is a different database. So after the user has logged in, I do not need the centeral database (login database), I juse need the user/organization specific database. So this is how I got it to work.

Best alternative to set a PostgreSQL schema using PHP PDO

I am using PHP PDO to access a PostgreSQL database with various schemas, so first i create a connection and then i set the correct schema, like below:
$Conn = new PDO('pgsql:host=localhost;port=5432;dbname=db', 'user', 'pass');
$result = $Conn->exec('SET search_path TO accountschema');
if ( ! $result) {
die('Failed to set schema: ' . $Conn->errorMsg());
}
Is this a good practice? Is there a better way to do this?
In order to specify the default schema you should set the search_path instead.
$Conn->exec('SET search_path TO accountschema');
You can also set the default search_path per database user and in that case the above statement becomes redundant.
ALTER USER user SET search_path TO accountschema;

CREATE and DROP TABLE using Zend Adapter

I'm trying to do some SQL queries using Zend adapter. The code that I'm trying to use is something like this:
$result = $this->$db->getConnection()->exec('CREATE TABLE TEST');
and I know that $db is set and works properly, because I can run other commands such as
$this->$db->listTables(); or
$result = $this->$db->fetchAssoc("SHOW COLUMNS FROM " .$schema);
As I was reading through Zend documentation, it was mentioned that some database transactions that are not prepared should be used through the first example (e.g. exec("...") ), but apparently I have problems running those.
Any thoughts?
This should work ...
$db = Zend_Db_Table::getDefaultAdapter();
$db->query('CREATE TABLE wolf (tag VARCHAR(9))');

how to work with multiple database

I am working on one company internal web software and in this I have given forum option for internal employee.Now I have to add second company to forum so that second company employee can also give some comment in forum.I have two database one for my company internal and second is second company database.
Please Help me how can I Implement this???
Always use resource returned by mysql_connect() so you know what database you use
// database 1
$db1 = mysql_connect();
// database 2
$db2 = mysql_connect();
// query db1
mysql_query($query,$db1);
Also try reading the docs about it
It depends on what database you are using..,,
and try to read some mysql function cause theres a function for linking databases..
You should use 2 (3, 4, 5 ...) db connections.
If your bases is not MySql only, you can use PDO extension:
$db1 = new PDO($param1, $param2, $param3);
$db2 = new PDO($param4, $param5, $param6);
And then you can use any of them, e.g.:
$db2->exec();

Categories