Database connections
Learn how to connect to a database
Interaction with a database is achieved with the help of the Opis\Database\Database class,
which provides various methods that will ease the process of manipulating tables and records.
The constructor of this class takes as an argument an instance of Opis\Database\Connection.
The Connection class is responsible both for establishing a connection to the database server,
as well as for sending and receiving data.
The constructor of the Connection class accepts parameters for specifying
the DSN and optionally for the username and password(if any).
use Opis\Database\Database;
use Opis\Database\Connection;
$connection = new Connection(
'mysql:host=localhost;dbname=test',
'username',
'password'
);
$db = new Database($connection);
You can also create a connection by using the fromPDO static method and
passing an instance of the PDO class as an argument to the method.
$connection = Connection::fromPDO($pdo);
PDO options
The DSN, the username and the password provided when instantiating a new
Opis\Database\Connection class, will be further used to build a PDO object that will actually
establish a connection to the database.
Opis Database allows you to specify options for the PDO object by calling the option method.
$connection = new Connection($dsn, $user, $password);
$connection->option(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ)
$connection->option(PDO::ATTR_STRINGIFY_FETCHES, false);
Setting multiple options simultaneously is done by calling the options method
and passing as an argument an array of options.
$connection = new Connection($dsn, $user, $password)
$connection->options([
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
PDO::ATTR_STRINGIFY_FETCHES => false
]);
Persistent connections
Making a connection persistent is done by using the persistent method.
$connection = new Connection($dsn, $user, $password);
$connection->persistent();
Logging
You can keep a log with all of the queries sent to a database by calling the logQueries method.
Retrieving the list of logged queries is done using the getLog method.
$connection = new Connection($dsn, $user, $password);
$connection->logQueries();
//Your queries...
foreach ($connection->getLog() as $entry) {
echo $entry;
}
Init commands
You also have the possibility to specify a list of commands that will be executed after connecting
to a database by using the initCommand method.
$connection = new Connection($dsn, $user, $password);
$connection->initCommand('SET NAMES UTF8');