DB::$dbName not considered if set after query is made
wadih opened this issue · comments
I have a script that sets DB::$dbName
later in the script, as the database might not exist at the beginning of the script, and start existing mid-way in the script.
But if I use DB::query()
while DB::$dbName
was not yet set for non-database queries like "show databases", and later set DB::$dbName
, it is not considered and the "No database selected" exception is thrown.
For example this works:
DB::$user = "my_user";
DB::$dbName = 'my_database';
print_r(DB::query("show tables;"));
But this throws an exception:
DB::$user = "my_user";
print_r(DB::query("show databases;"));
DB::$dbName = 'my_database';
print_r(DB::query("show tables;"));
The exception thrown is:
PHP Fatal error: Uncaught MeekroDBException: No database selected
I can solve it by manually querying "use my_database":
DB::$user = "my_user";
DB::query("show databases;");
DB::query("use my_database");
print_r(DB::query("show tables;"));
So for DB::$dbName
to work, it has to be called before any other query is made with DB.
I disabled opcache.enable_cli
as I'm running this on command line, but looks like it's not related to opcache.
I can manually fix it by doing DB::query("use my_database");
Not sure if this was the desired behavior, so I am reporting it.
So DB::$dbName
is just like the other connection variables such as DB::$user
-- they're used to establish the connection and then ignored afterwards. So for example, if you change DB::$user
after you're connected then it won't re-connect with the new user.
If you want to change the database after connecting, you should use DB::useDB("database")
. If you're not sure whether you've already connected or not, just use DB::useDB()
anyway. Since it just runs a query for you, it'll connect if you're not already connected.
I'll update the documentation to be more clear about this, then close this.