Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 17 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ the corresponding `SQL`
* The third position is the value of your condition,
* and the forth position is for the operator `and`,`or`and `not`, by default it `and`, and it is required whene there is multiple conditiontions.
```php
$where=[
$where = [
['id',"=",2],
['username',"like",'admin','or'],
['email',"like",'admin']
Expand All @@ -90,15 +90,21 @@ in case there is problem as `error` method can be called to check if there is an
$result = $db->get("users")->field(['email','address'])->orderBy("id")->offset(0)->limit(30)->DESC()->result();
if($db->error()) print_r($db->error());
```

Sometimes you want to count record instead if listing them, `count` method is part of get with return an object count.
Comment thread
bim-g marked this conversation as resolved.
use count object to access the value return.
```php
$count_users = $db->count("users")->field(['email','address'])->where($where)->result();
echo $count_users->count;
//
```
* `insert` is used to record data. the method take table name as parameter,
use field method to pass data to be saved.
in case your information are correct the `db` instance you can call`lastId` method to get the id of the inserted record.
```php
$data = [
"userid" => 2,
"message" => "hello from wepesi",
"datecreated" => Date('Y-m-d H:i:s')
"date_created" => Date('Y-m-d H:i:s')
];
try {
$db->insert("message")->field($data)->result();
Expand Down Expand Up @@ -172,14 +178,15 @@ the example bellow describe how it can be used. with the `query` method use the
### Transaction
For so many reasons you would like to implement a transaction in case one of your operation failed.
Take caution only `InnoDB` support transaction in order to see the result you should be sure your `ENGINE` is innoDB,
in case you are not sure you can convert your tables only with `convertToInnoDB` method.
in case you are not sure about the database engine you can convert your tables only with `convertMyISAMToInnoDB` method.
That method will help convert `MyISAM` engine to `InnoDB`.
There are two ways to use transaction as been defined.
you can manage by your own how, end when to uply transaction or use a buildin `transaction` method.
you can manage by your own how, end when to apply transaction or use a builtin `transaction` method.
It is recommended to use try catch in or to fulfil the operation.
* #### One
* #### pdo transaction
The transaction has tree method to used in order to work properly, we have:
- `beginTransaction` : this method is used to start a transaction, and is shoudl be place at the beginning operation where the transaction will occur.
- `commit` : used this method when the operation succeed.
- `commit` : used this method when the operation succeeds.
- `rollBack` : is used to cancel all the operation.
```php
try{
Expand Down Expand Up @@ -218,10 +225,10 @@ The transaction has tree method to used in order to work properly, we have:
}
```

* #### two
`transaction` : is method support closure method to be passed as parameter.
* #### Transaction as callback
method support closure method to be passed as parameter.
You don't need to manage every situation of the transaction,
`transction` method help you the focus implementation, and it will do the job for you.
the method help you the focus implementation, and it will do the job for you.
```php
$user = [
"fullname" => "Celestin Doe",
Expand Down
96 changes: 61 additions & 35 deletions src/DB.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
class DB
{
private static ?DB $_instance = null;
private $_query,
$query_transaction;
private ?string $_query;
private $query_transaction;
private ?string $_error;
private array $_results;
private int $_lastID;
Expand All @@ -22,7 +22,7 @@ class DB
private int $_count;
private string $db_name;
use BuildQuery;
private function __construct(string $host="",string $db_name="",string $user_name="",string $password="")
private function __construct(string $host = "",string $db_name = "",string $user_name = "",string $password = "")
{
try {
$this->_results = [];
Expand All @@ -46,26 +46,26 @@ private function __construct(string $host="",string $db_name="",string $user_nam
* @param array $config this config will store the database configuration, the host, database name, username and password.
* @return DB|null
*/
static function getInstance(array $config): ?DB
public static function getInstance(array $config): ?DB
{
try{
if(!isset($config['host']) || !$config['host']) throw new \Exception("host config params is not defined");
if(!isset($config['db_name']) || !$config['db_name']) throw new \Exception("db_name config params does not exist or is not set");
if(!isset($config['username']) || !$config['username']) throw new \Exception("database username config params does not exist or is not set");
if(!isset($config['password']) ) throw new \Exception("database password config params does not exist or is not set");

$hot=$config["host"];
$db_name=$config["db_name"];
$user_name=$config["username"];
$password=$config["password"];
$hot = $config["host"];
$db_name = $config["db_name"];
$user_name = $config["username"];
$password = $config["password"];

if(!isset(self::$_instance)){
self::$_instance=new DB($hot,$db_name,$user_name,$password);
self::$_instance = new DB($hot,$db_name,$user_name,$password);
}
return self::$_instance;

}catch (\Exception $ex){
print_r(["exception"=>$ex->getMessage()]);
print_r(["exception" => $ex->getMessage()]);
die();
}
}
Expand All @@ -75,7 +75,7 @@ static function getInstance(array $config): ?DB
* @return DB_Select
* @throws Exception
*/
function get(string $table_name): DB_Select
public function get(string $table_name): DB_Select
{
return $this->select_option($table_name);
}
Expand All @@ -85,14 +85,14 @@ function get(string $table_name): DB_Select
* @return DB_Select
* @throws Exception
*/
function count(string $table_name): DB_Select
public function count(string $table_name): DB_Select
{
return $this->select_option($table_name, "count");
}

/**
* @string : $table=> this is the name of the table where to get information
* @string : @action=> this is the type of action tu do while want to do a request
* @param string $table_name table name of the table where to get information
* @param string $action action this is the type of action tu do while want to do a request
* @throws Exception
*/
private function select_option(string $table_name, string $action = "select"): ?DB_Select
Expand All @@ -105,39 +105,39 @@ private function select_option(string $table_name, string $action = "select"): ?
}

/**
* @param string $table : this is the name of the table where to get information
* @param string $table this is the name of the table where to get information
* @return DB_Insert
*
* this method will help create new row data
*/
function insert(string $table): DB_Insert
public function insert(string $table): DB_Insert
{
$this->query_transaction = new DB_Insert($this->pdo, $table);
return $this->query_transaction;
}

/**
* @param string $table : this is the name of the table where to get information
* @param string $table this is the name of the table where to get information
* @return DB_Delete
*/
function delete(string $table): DB_Delete
public function delete(string $table): DB_Delete
{
$this->query_transaction= new DB_Delete();
return $this->query_transaction;
}
//

/**
* @param string $table : this is the name of the table where to get information
* @param string $table this is the name of the table where to get information
* @return DB_Update
*/
function update(string $table): DB_Update
public function update(string $table): DB_Update
{
$this->query_transaction = new DB_Update();
return $this->query_transaction;
}
//
function query($sql, array $params = []): DB
public function query($sql, array $params = []): DB
{
$q = $this->executeQuery($this->pdo,$sql,$params);
$this->_results = $q['result'];
Expand All @@ -150,18 +150,21 @@ function query($sql, array $params = []): DB

/**
* @return int
* get the last id after insert new record
*/
function lastId(): int
public function lastId(): int
{
if (isset($this->query_transaction) && method_exists($this->query_transaction, 'lastId')) {
$this->_lastID = $this->query_transaction->lastId();
}
return $this->_lastID;
}

/**
* return an error status when an error occur while doing an query
* @return string|null
* return an error status when an error occur while doing a query
*/
function error()
public function error(): ?string
{
if(isset($this->query_transaction) ){
$this->_error = $this->query_transaction->error();
Expand All @@ -172,32 +175,53 @@ function error()
/**
* @return array
*/
function result(): array
public function result(): array
{
return $this->_results;
}
function rowCount(){

/**
* @return int
* return total of rows selected
*/
public function rowCount()
{
if(isset($this->query_transaction) && method_exists($this->query_transaction,"count") ){
$this->_count = $this->query_transaction->count();
}
return $this->_count;
}

function beginTransaction(): bool
/**
* @return bool
* start a transaction
*/
public function beginTransaction(): bool
{
return $this->pdo->beginTransaction();
}
function commit(){

/**
* @return bool
* validate a transaction when success query
*/
public function commit(){
return $this->pdo->commit();
}
function rollBack(){

/**
* @return bool
* cancel a transaction when query fall
*/
public function rollBack(){
return $this->pdo->rollBack();
}

/**
* @throws Exception
* implement transaction with callback function to manage all at once
*/
function transaction(\Closure $callable){
public function transaction(\Closure $callable){
try{
$this->pdo->beginTransaction();
$callable($this);
Expand All @@ -212,18 +236,20 @@ function transaction(\Closure $callable){

/**
* @throws Exception
* convert your database ENGINE to MyISAM in case you want your database to support transactions.
*/
function convertToInnoDB(){
public function convertMyISAMToInnoDB(){
try {
$params =[$this->db_name,"MyISAM"];
$params = [$this->db_name,"MyISAM"];
$sql = "SELECT TABLE_NAME FROM information_schema.tables WHERE table_schema = ? AND `ENGINE` = ?";
$result = self::query($sql,$params)->result();
foreach ($result as $table){
$sql = "ALTER TABLE $table->TABLE_NAME ENGINE=InnoDB";
$this->query($sql);
$params = ["InnoDB"];
$sql = "ALTER TABLE $table->TABLE_NAME ENGINE = ?";
$this->query($sql,$params);
}
}catch (\Exception $ex){
throw $ex;
print_r($ex);
}
}
}
8 changes: 4 additions & 4 deletions src/DB_Select.php
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ function field(array $fields = []): DB_Select
}

/**
* @param array $group
* @param string $field
* @return $this
*/
function groupBY(string $field): DB_Select
Expand All @@ -142,7 +142,7 @@ function groupBY(string $field): DB_Select

/**
*
* @param string $order
* @param string|null $order
* @return $this
*/
function orderBy(string $order = null): DB_Select
Expand Down Expand Up @@ -263,13 +263,13 @@ private function build()

/**
*
* @return bool|int
* @return array|int
* execute query to get result
*/
function result()
{
$this->build();
return $this->action == 'count' ? count($this->_results) : $this->_results;
return $this->action == 'count' ? $this->_results[0] : $this->_results;
}

/**
Expand Down