A simple package that abstracts away the process of connecting to a database using PDO
and interacting with the connection.
All code is written using PSR1 and PSR2 guidelines.
Via Composer
$ composer require emmanix2002/database-adapter
We start by creating an instance of the class; it provides a utility create()
method that takes in the settings as an array and
fills in defaults where needed.
It is possible to change the defaults by calling the setDefault()
static method.
$config = ['host' => 'localhost', 'user' => 'user', 'password' => 'password', 'schema' => 'schema_name'];
$adapter = Emmanix2002\MySqlAdapter::create($config);
// OR
$adapter = new Emmanix2002\MySqlAdapter('host', 'schema_name', 'user', 'password');
$record = $adapter->selectOne('SELECT * FROM `Users` WHERE `user_id`=?', 21134);
var_dump($record);
use Emmanix2002\MySqlAdapter;
MySqlAdapter::setDefault('host', 'default_hostname');
MySqlAdapter::setDefault('schema', 'default_schema');
MySqlAdapter::setDefault('user', 'default_user');
MySqlAdapter::setDefault('password', 'default_password');
$adapterDefault = MySqlAdapter::create();
// create an adapter using the defaults
$adapter = MySqlAdapter::create(['host' => 'another_hostname']);
// equivalent to new MySqlAdapter('another_hostname', 'default_schema', 'default_user', 'default_password');
There are a few methods that help with querying, they are:
exec()
selectAll()
selectOne()
exec()
should be called directly for all queries that do not return an actual response i.e. every query excluding SELECT
statements. It is called by both select*()
methods, but it's much easier using them for SELECTing
as opposed to calling
exec()
yourself. exec()
uses prepared statements
on all queries passed to it.
Below are examples:
$sql = 'SELECT * FROM `users` WHERE `user_email`=? AND `user_status`=?';
$record = $adapter->selectOne($sql, 'username@example.com', 1);
// it is also possible to do the same like so:
$args = ['username@example.com', 1];
$record = $adapter->selectOne($sql, ...$args);
// both will return the same value
exec()
always returns a value; depending on the arguments passed:
true
: is returned if the query was successfully executed and the$isSelect
parameter is set toFALSE
false
: is returned if the query execution failed, irrespective of the value of the$isSelect
parameterarray
: is returned if the query was successful and the$isSelect
parameter is set toTRUE
.select*()
methods always set$isSelect
toTRUE
Please see CHANGELOG for more information what has changed recently.
$ composer test
Please see CONTRIBUTING and CONDUCT for details.
If you discover any security related issues, please email emmanix2002@gmail.com instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.