Edit active database on the fly

2019-09-05 05:54发布

问题:

So I'm working on a little web application in which you can manage your database.

Now I can use the following function to retrieve all databases

DB::select('SHOW DATABASES')

But I now want to be able to get the tables for each of those databases and eventually do more with those databases, but I figured if I get this working that wouldn't be a problem.

Normally you'd have the different database in your config, but since I want my application work with "any" database and make sure I don't have to manually add all the databases etc since that's the kind of work I want my web app done for me.

I've tried tricking around it a bit without success for example.

DB:select('USE dbName; SHOW TABLES');
DB::select('SELECT dbName(); SHOW TABLES'); 

Obviously this didn't work, but is there any "proper" solution to this? I thought editing the .env variable on the fly might've been an option, but I can't seem to find a "legit" way to do that either.

回答1:

You don't need this.

I thought editing the .env variable on the fly might've been an option, but I can't seem to find a "legit" way to do that either.

What you need is this

DB::purge('mysql');//IMP

Config::set('database.connections.mysql.host', $host);
Config::set('database.connections.mysql.database', $database);
Config::set('database.connections.mysql.username', $username);
Config::set('database.connections.mysql.password', $password);

You just need to figure out a way to get the values for $host, $database, $username, and $password dynamically.

One way to do that is have a database which stores all these values and point the default database connection (say mysql in config/database.php) to it. Then read values from it on the fly and set the connections accordingly.