Connect to the Server
connect( … )
Once you have established the database type, the next step is to connect to the database server. We can do that using the connect method:
1 |
DB::MySQL()->connect() |
Please note that the parameters the connect method takes may vary, as each database works differently (ie Firebird and SQLite). However, for MySQL we would follow the standard mysql_connect parameter order:
1 |
DB::MySQL()->connect('host', 'username', 'password'); |
Because you can have multiple connections in DB::DBAL, you may want to save the connection to reference it later. You can do this using the saveConnectionAs() method:
1 |
DB::MySQL()->connect('host', 'username', 'password')->saveConnectionAs('conn1'); |
We can now continue to add connections (make sure to save them if you wish to be able to switch back and forth from connections. To switch to a saved connection we can use the useConnection() method:
useConnection( string $connection_name )
1 |
DB::MySQL()->useConnection('conn1'); |
Note, when calling connect you are automatically connected, and the new connection becomes your active connection. You do not need to save connections if you only intend to use it once or without switching back and forth.