I have the following statement which creates a new instance of PDO, connecting to the local MySQL server:
Database::$db = new PDO('mysql:host=localhost', "root", DBPW, array(PDO::ATTR_PERSISTENT => true));
After that, I run an SQL statement on the newly established connection which ensures the expected databases and tables exist (snippet):
Database::$db->exec("
CREATE DATABASE IF NOT EXISTS phpforum; -- Create the database if it doesn't exist
");
After that's succeeded, how would I replace my pre-existing generic PDO connection in Database::$db
with the database specific phpforum
one? Would I have to close the current connection and re-create it with the database in the connection string, or is there a much easier way to quickly specify a database on the currently opened connection so I don't have to explicity refer to the database every time I want to query it?
BTW, what I've posted above is the small useful snippets of my code. Please do not say "that can crash etc. etc.", I've set up the exception handlers to deal with such cases as the PDO::__constructor
or Database::$db->exec
methods failing.