From 46cdd8b3f040a09038c857701033cbc20f520203 Mon Sep 17 00:00:00 2001 From: Eduardo Malherbi Date: Wed, 28 Apr 2021 23:01:25 -0300 Subject: [PATCH 1/5] init --- src/INI.php | 51 ------ src/MyMysql.ini | 6 - src/MyMysql.php | 136 ++++++++------ src/MySql.php | 470 ++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 554 insertions(+), 109 deletions(-) delete mode 100755 src/INI.php delete mode 100755 src/MyMysql.ini create mode 100755 src/MySql.php diff --git a/src/INI.php b/src/INI.php deleted file mode 100755 index a5bc1ad..0000000 --- a/src/INI.php +++ /dev/null @@ -1,51 +0,0 @@ - $val) { - if (is_array($val)) { - $string .= self::write_get_string($ini[$key], $prefix.$key.'.'); - } else { - $string .= $prefix.$key.' = '.str_replace(self::RETURN_NEWLINE, "\\\r\\\n", self::set_value($val)).self::RETURN_NEWLINE; - } - } - - return $string; - } - - public static function set_value($val) - { - if (true === $val) { - return 'true'; - } elseif (false === $val) { - return 'false'; - } - - return $val; - } -} diff --git a/src/MyMysql.ini b/src/MyMysql.ini deleted file mode 100755 index d581d09..0000000 --- a/src/MyMysql.ini +++ /dev/null @@ -1,6 +0,0 @@ -[INI] -DB_LOG = false -DB_HOST = "127.0.0.1" -DB_NAME = "database" -DB_USER = "user" -DB_PASS = "password" \ No newline at end of file diff --git a/src/MyMysql.php b/src/MyMysql.php index d943461..7416150 100755 --- a/src/MyMysql.php +++ b/src/MyMysql.php @@ -8,7 +8,6 @@ namespace MyMysql; -use Exception; use PDO; use stdClass; @@ -31,12 +30,8 @@ public function __construct($ini = array(), $dl = '') $this->RT = realpath(dirname(__FILE__)); $this->DL = empty($dl) ? realpath(dirname(__FILE__)) : $dl; - if (!empty($ini)) { - $this->setIni($ini); - } - - $this->ini = $this->getIni(); - $this->connect(); + $this->ini = $ini; + $this->connection(); } /* error */ @@ -50,12 +45,17 @@ public function getError() /* connnect */ - public function connect() + public function connection() { - $this->logger('MyMysql | method: connect'); + $this->logger('MyMysql | method: connection'); + + if (!empty($this->db)) { + return $this->db; + } + $this->db = new PDO('mysql:host='.$this->ini['DB_HOST'].';dbname='.$this->ini['DB_NAME'], $this->ini['DB_USER'], $this->ini['DB_PASS'], array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')); - return $this->isConnect(); + return $this->db; } public function isConnect() @@ -73,21 +73,6 @@ public function disconnect() return !$this->isConnect(); } - /* ini */ - - public function getIni() - { - try { - $this->logger('MyMysql | method: getIni'); - - return parse_ini_file($this->RT.$this->DS.'MyMysql.ini'); - } catch (Exception $e) { - $err = $e->getMessage(); - $this->logger('MyMysql | getIni', $err); - die(print_r($e->getMessage())); - } - } - /* fetch */ public function fetchRow($table, $where = array(), $orderBy = '') @@ -193,6 +178,38 @@ public function fetchAll2($sql, $where = array()) return (!$exec) ? false : $stmt->fetchAll(PDO::FETCH_OBJ); } + /* + * BY BELUSSO: RETORNA 2, 3, 5 SELECTS NA MESMA PEGADA. + * NUM ARRAY, DE ACORDO COM A ORDEM DOS MESMOS + */ + public function fetchAll3($sql, $where = array()) + { + $log = $sql; + + $connection = $this->db; + $stmt = $connection->prepare('SET SQL_BIG_SELECTS = 1'); + $stmt->execute(); + $stmt = $connection->prepare($sql); + if (!empty($where)) { + foreach ($where as $key => &$value) { + $key = str_replace(':', '', $key); + $stmt->bindParam($key, $value); + $log = preg_replace('/:'.$key.'\b/i', "'$value'", $log); + } + } + + $this->logger($log); + $exec = $stmt->execute(); + $results = array(); + + do { + $rowset = $stmt->fetchAll(PDO::FETCH_OBJ); + $results[] = $rowset ?? array(); + } while ($stmt->nextRowset()); + + return $results; + } + public function insert($table, $item) { $this->logger('MyMysql | method: insert'); @@ -230,10 +247,15 @@ public function insert($table, $item) $log = $this->error; $this->logger($log); - } else { - $item->id = $conn->lastInsertId(); - $item->ID = $item->id; + + echo '
';
+            echo print_r($log);
+            echo print_r($this->error);
+            echo '
'; + die(); } + $item->id = $conn->lastInsertId(); + $item->ID = $item->id; return (!$exec) ? false : $item; } @@ -280,10 +302,15 @@ public function update($table, $item, $where, $id) $log = $this->error; $this->logger($log); - } else { - $item->id = $id; - $item->ID = $id; + + echo '
';
+            echo print_r($log);
+            echo print_r($this->error);
+            echo '
'; + die(); } + $item->id = $id; + $item->ID = $id; return (!$exec) ? false : $item; } @@ -322,6 +349,12 @@ public function delete($table, $where) $log = $this->error; $this->logger($log); + + echo '
';
+            echo print_r($log);
+            echo print_r($this->error);
+            echo '
'; + die(); } return $exec; @@ -364,7 +397,7 @@ public function sql($method = '', $sql = '', $table = '', $where = array(), $ord $result->status = false; } - if (is_bool($result->model)) { + if (is_bool($result->model) && (false == $result->model)) { $result->status = false; $result->msg = "Ops. Ocorreu um erro. Method: $method. Sql: $sql. Table: $table. Where: ".json_encode($where).". Order By: $orderBy. Obj: ".json_encode($obj).". Id: $id "; } @@ -396,13 +429,6 @@ public function rollback() /* private */ - private function setIni($ini = array()) - { - $this->logger('MyMysql | method: setIni'); - - INI::write($this->RT.$this->DS.'MyMysql.ini', array('INI' => $ini)); - } - private function logger($str, $err = '') { if (true == $this->ini['DB_LOG']) { @@ -428,19 +454,25 @@ private function logger($str, $err = '') private function deleteColumnFromSqlIfNotExist($table, &$item) { - foreach ($item as $key => $value) { - $sql = ''; - $sql .= " SELECT COUNT(*) AS COLUMN_EXIST - FROM information_schema.COLUMNS - WHERE TABLE_NAME = '$table' - AND COLUMN_NAME = '$key' "; - - $stmt = $this->db->prepare($sql); - $stmt->execute(); - $columnExist = $stmt->fetchObject(); - $columnExist = $columnExist->COLUMN_EXIST; - if (empty($columnExist)) { - unset($item->$key); + $sql = " SELECT COLUMN_NAME + FROM information_schema.COLUMNS + WHERE TABLE_NAME = '$table' "; + + $stmt = $this->db->prepare($sql); + $exec = $stmt->execute(); + + $arr = (!$exec) ? false : $stmt->fetchAll(PDO::FETCH_OBJ); + + if (!empty($arr)) { + $columns = array(); + foreach ($arr as $key => $value) { + $columns[] = $value->COLUMN_NAME; + } + + foreach ($item as $key => $value) { + if (!in_array($key, $columns)) { + unset($item->$key); + } } } } diff --git a/src/MySql.php b/src/MySql.php new file mode 100755 index 0000000..4855cf9 --- /dev/null +++ b/src/MySql.php @@ -0,0 +1,470 @@ +ini = null; + $this->db = null; + $this->error = ''; + + $this->loadIni(); + } + + public function loadIni() + { + $this->ini = parse_ini_file(CONFIG.DS.'application.ini'); + } + + /* error */ + + public function getError() + { + $this->logger('MyMysql | method: getError'); + + return $this->error; + } + + /* connnect */ + + public function connection() + { + $this->logger('MyMysql | method: connection'); + + if (!empty($this->db)) { + return $this->db; + } + + $this->db = new PDO('mysql:host='.$this->ini['DB_HOST'].';dbname='.$this->ini['DB_NAME'], $this->ini['DB_USER'], $this->ini['DB_PASS'], array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')); + + // For Amazon. + $stmt = $this->db->prepare("SET time_zone = 'America/Montevideo'"); + $stmt->execute(); + + return $this->db; + } + + public function isConnect() + { + $this->logger('MyMysql | method: isConnect'); + + return empty($this->db) ? false : true; + } + + public function disconnect() + { + $this->logger('MyMysql | method: disconnect'); + $this->db = null; + + return !$this->isConnect(); + } + + /* fetch */ + + public function fetchRow($table, $where = array(), $orderBy = '') + { + $this->logger('MyMysql | method: fetchRow'); + + $sql = " SELECT * FROM $table WHERE 1 = 1 "; + if (!empty($where)) { + foreach ($where as $key => $value) { + $key = str_replace(':', '', $key); + $sql .= " AND $key = :$key "; + } + } + $sql .= $orderBy; + $log = $sql; + + $stmt = $this->db->prepare($sql); + if (!empty($where)) { + foreach ($where as $key => &$value) { + $key = str_replace(':', '', $key); + $stmt->bindParam($key, $value); + $log = preg_replace('/:'.$key.'\b/i', "'$value'", $log); + } + } + + $this->logger($log); + $exec = $stmt->execute(); + + return (!$exec) ? false : $stmt->fetchObject(); + } + + public function fetchRow2($sql, $where = array()) + { + $this->logger('MyMysql | method: fetchRow2'); + + $log = $sql; + + $stmt = $this->db->prepare($sql); + if (!empty($where)) { + foreach ($where as $key => &$value) { + $key = str_replace(':', '', $key); + $stmt->bindParam($key, $value); + $log = preg_replace('/:'.$key.'\b/i', "'$value'", $log); + } + } + + $this->logger($log); + $exec = $stmt->execute(); + + return (!$exec) ? false : $stmt->fetchObject(); + } + + public function fetchAll($table, $where = array(), $orderBy = '') + { + $this->logger('MyMysql | method: fetchAll'); + + $sql = " SELECT * FROM $table WHERE 1 = 1 "; + if (!empty($where)) { + foreach ($where as $key => $value) { + $key = str_replace(':', '', $key); + $sql .= " AND $key = :$key "; + } + } + $sql .= $orderBy; + $log = $sql; + + $stmt = $this->db->prepare($sql); + if (!empty($where)) { + foreach ($where as $key => &$value) { + $key = str_replace(':', '', $key); + $stmt->bindParam($key, $value); + $log = preg_replace('/:'.$key.'\b/i', "'$value'", $log); + } + } + + $this->logger($log); + $exec = $stmt->execute(); + + return (!$exec) ? false : $stmt->fetchAll(PDO::FETCH_OBJ); + } + + public function fetchAll2($sql, $where = array()) + { + $this->logger('MyMysql | method: fetchAll2'); + + $log = $sql; + + $connection = $this->db; + $stmt = $connection->prepare('SET SQL_BIG_SELECTS = 1'); + $stmt->execute(); + $stmt = $connection->prepare($sql); + if (!empty($where)) { + foreach ($where as $key => &$value) { + $key = str_replace(':', '', $key); + $stmt->bindParam($key, $value); + $log = preg_replace('/:'.$key.'\b/i', "'$value'", $log); + } + } + + $this->logger($log); + $exec = $stmt->execute(); + + return (!$exec) ? false : $stmt->fetchAll(PDO::FETCH_OBJ); + } + + /* + * BY BELUSSO: RETORNA 2, 3, 5 SELECTS NA MESMA PEGADA. + * NUM ARRAY, DE ACORDO COM A ORDEM DOS MESMOS + */ + public function fetchAll3($sql, $where = array()) + { + $log = $sql; + + $connection = $this->db; + $stmt = $connection->prepare('SET SQL_BIG_SELECTS = 1'); + $stmt->execute(); + $stmt = $connection->prepare($sql); + if (!empty($where)) { + foreach ($where as $key => &$value) { + $key = str_replace(':', '', $key); + $stmt->bindParam($key, $value); + $log = preg_replace('/:'.$key.'\b/i', "'$value'", $log); + } + } + + $this->logger($log); + $exec = $stmt->execute(); + $results = array(); + + do { + $rowset = $stmt->fetchAll(PDO::FETCH_OBJ); + $results[] = $rowset ?? array(); + } while ($stmt->nextRowset()); + + return $results; + } + + public function insert($table, $item) + { + $this->logger('MyMysql | method: insert'); + + $this->deleteColumnFromSqlIfNotExist($table, $item); + + $sql = ''; + $sql .= " INSERT INTO $table ("; + foreach ($item as $key => $value) { + $sql .= "$key,"; + } + $sql = rtrim($sql, ','); + $sql .= ') VALUES ('; + foreach ($item as $key => $value) { + $sql .= ":$key,"; + } + $sql = rtrim($sql, ','); + $sql .= ')'; + $log = $sql; + + $db = $this->db; + $stmt = $db->prepare($sql); + foreach ($item as $key => &$value) { + $stmt->bindParam($key, $value); + $log = preg_replace('/:'.$key.'\b/i', "'$value'", $log); + } + + $this->logger($log); + $exec = $stmt->execute(); + + $this->error = ''; + if (!$exec) { + $errorInfo = $stmt->errorInfo(); + $this->error = $errorInfo[1].' - '.$errorInfo[2]; + + $log = $this->error; + $this->logger($log); + + echo '
';
+            echo print_r($log);
+            echo print_r($this->error);
+            echo '
'; + die(); + } + $item->id = $db->lastInsertId(); + $item->ID = $item->id; + + return (!$exec) ? false : $item; + } + + public function update($table, $item, $where, $id) + { + $this->logger('MyMysql | method: update'); + + $this->deleteColumnFromSqlIfNotExist($table, $item); + + $sql = ''; + $sql .= " UPDATE $table SET "; + foreach ($item as $key => $value) { + $sql .= "$key=:$key,"; + } + $sql = rtrim($sql, ','); + $sql .= ' WHERE 1 = 1 '; + foreach ($where as $key => $value) { + $key = str_replace(':', '', $key); + $sql .= " AND $key = :$key "; + } + $log = $sql; + + $db = $this->db; + $stmt = $db->prepare($sql); + foreach ($item as $key => &$value) { + $key = str_replace(':', '', $key); + $stmt->bindParam($key, $value); + $log = preg_replace('/:'.$key.'\b/i', "'$value'", $log); + } + foreach ($where as $key => &$value) { + $key = str_replace(':', '', $key); + $stmt->bindParam($key, $value); + $log = preg_replace('/:'.$key.'\b/i', "'$value'", $log); + } + + $this->logger($log); + $exec = $stmt->execute(); + + $this->error = ''; + if (!$exec) { + $errorInfo = $stmt->errorInfo(); + $this->error = $errorInfo[1].' - '.$errorInfo[2]; + + $log = $this->error; + $this->logger($log); + + echo '
';
+            echo print_r($log);
+            echo print_r($this->error);
+            echo '
'; + die(); + } + $item->id = $id; + $item->ID = $id; + + return (!$exec) ? false : $item; + } + + public function delete($table, $where) + { + $this->logger('MyMysql | method: delete'); + + if (empty($where)) { + $this->logger('Impossible to delete without the clause where...'); + + return false; + } + + $sql = "DELETE FROM $table WHERE 1 = 1 "; + foreach ($where as $key => $value) { + $key = str_replace(':', '', $key); + $sql .= " AND $key = :$key "; + } + $log = $sql; + + $stmt = $this->db->prepare($sql); + foreach ($where as $key => &$value) { + $key = str_replace(':', '', $key); + $stmt->bindParam($key, $value); + $log = preg_replace('/:'.$key.'\b/i', "'$value'", $log); + } + + $this->logger($log); + $exec = $stmt->execute(); + + $this->error = ''; + if (!$exec) { + $errorInfo = $stmt->errorInfo(); + $this->error = $errorInfo[1].' - '.$errorInfo[2]; + + $log = $this->error; + $this->logger($log); + + echo '
';
+            echo print_r($log);
+            echo print_r($this->error);
+            echo '
'; + die(); + } + + return $exec; + } + + public function execute($sql) + { + $this->logger('MyMysql | method: execute'); + $this->logger($sql); + + $stmt = $this->db->prepare($sql); + + return $stmt->execute(); + } + + public function sql($method = '', $sql = '', $table = '', $where = array(), $orderBy = '', $obj = null, $id = 0) + { + $this->logger('MyMysql | method: sql'); + + $result = new stdClass(); + $result->msg = ''; + $result->status = true; + $result->model = null; + + if ('fetchRow' === $method) { + $result->model = $this->fetchRow($table, $where, $orderBy); + } elseif ('fetchAll' === $method) { + $result->model = $this->fetchAll($table, $where, $orderBy); + } elseif ('fetchRow2' === $method) { + $result->model = $this->fetchRow2($sql); + } elseif ('fetchAll2' === $method) { + $result->model = $this->fetchAll2($sql); + } elseif ('insert' === $method) { + $result->model = $this->insert($table, $obj); + } elseif ('update' === $method) { + $result->model = $this->update($table, $obj, $where, $id); + } elseif ('delete' === $method) { + $result->model = $this->delete($table, $where); + } else { + $result->status = false; + } + + if (is_bool($result->model) && (false == $result->model)) { + $result->status = false; + $result->msg = "Ops. Ocorreu um erro. Method: $method. Sql: $sql. Table: $table. Where: ".json_encode($where).". Order By: $orderBy. Obj: ".json_encode($obj).". Id: $id "; + } + + return $result; + } + + /* transaction */ + + public function beginTransaction() + { + return $this->db->beginTransaction(); + } + + public function closeTransaction() + { + return $this->db->closeTransaction(); + } + + public function commit() + { + return $this->db->commit(); + } + + public function rollback() + { + return $this->db->rollback(); + } + + /* private */ + + private function logger($msg) + { + if (true == $this->ini['DB_LOG']) { + $path = LOG.DS; + $file = date('Y-m-d').'.log'; + + @mkdir($path, 0777, true); + @chmod($path, 0777); + + $file = @fopen($path.$file, 'a+'); + fwrite($file, $msg); + fwrite($file, "\n"); + fclose($file); + } + } + + /* private func */ + + private function deleteColumnFromSqlIfNotExist($table, &$item) + { + $sql = " SELECT COLUMN_NAME + FROM information_schema.COLUMNS + WHERE TABLE_NAME = '$table' "; + + $stmt = $this->db->prepare($sql); + $exec = $stmt->execute(); + + $arr = (!$exec) ? false : $stmt->fetchAll(PDO::FETCH_OBJ); + + if (!empty($arr)) { + $columns = array(); + foreach ($arr as $key => $value) { + $columns[] = $value->COLUMN_NAME; + } + + foreach ($item as $key => $value) { + if (!in_array($key, $columns)) { + unset($item->$key); + } + } + } + } +} From 05cc583b609a7d2580f7c7a0be39c49fcbf2cde0 Mon Sep 17 00:00:00 2001 From: Eduardo Malherbi Date: Thu, 29 Apr 2021 14:11:07 -0300 Subject: [PATCH 2/5] update class mysql and log table --- README.md | 41 ++--- sql/log.sql | 7 + src/MyMysql.php | 160 ++++++++++------- src/MySql.php | 470 ------------------------------------------------ 4 files changed, 116 insertions(+), 562 deletions(-) create mode 100644 sql/log.sql delete mode 100755 src/MySql.php diff --git a/README.md b/README.md index f6e4cb0..6995261 100755 --- a/README.md +++ b/README.md @@ -14,10 +14,6 @@ composer require emalherbi/mymysql require_once 'vendor/autoload.php'; try { - if (@date_default_timezone_get() !== @ini_get('date.timezone')) { - @date_default_timezone_set('America/Sao_Paulo'); - } - $mysql = new MyMysql\MyMysql(array( 'DB_LOG' => true, 'DB_HOST' => '192.168.1.100', @@ -28,22 +24,22 @@ try { /* fetch */ - $result = $mysql->fetchRow('ENTIDADES', array('ID_ENTIDADE' => '2'), 'ORDER BY ID_ENTIDADE'); + $result = $mysql->fetchRow('CLIENTS', array('ID_CLIENTS' => '2'), 'ORDER BY ID_CLIENTS'); echo '
';
     echo print_r($result);
     echo '
'; - $result = $mysql->fetchRow2('SELECT * FROM ENTIDADES'); + $result = $mysql->fetchRow2('SELECT * FROM CLIENTS'); echo '
';
     echo print_r($result);
     echo '
'; - $result = $mysql->fetchAll('ENTIDADES', array('ID_ENTIDADE' => '2'), 'ORDER BY ID_ENTIDADE'); + $result = $mysql->fetchAll('CLIENTS', array('ID_CLIENTS' => '2'), 'ORDER BY ID_CLIENTS'); echo '
';
     echo print_r($result);
     echo '
'; - $result = $mysql->fetchAll2('SELECT * FROM ENTIDADES LIMIT 2'); + $result = $mysql->fetchAll2('SELECT * FROM CLIENTS LIMIT 2'); echo '
';
     echo print_r($result);
     echo '
'; @@ -51,42 +47,40 @@ try { /* insert */ $item = new stdClass(); - $item->ID_MESA = 0; - $item->ID_EMPRESA = 2; - $item->CODIGOMESA = 999; - $item->DESCRICAO = 'TESTE'; - $item->ATIVO = 1; + $item->ID_BOARD = 0; + $item->CODE = 999; + $item->DESCRIPTION = 'TEST'; + $item->ACTIVE = 1; - $result = $mysql->insert('MESAS', $item); + $result = $mysql->insert('BOARD', $item); echo '
';
     echo print_r($result);
     echo '
'; /* update */ - $ID_MESA = 530; + $ID_BOARD = 530; $item = new stdClass(); - $item->ID_EMPRESA = 2; - $item->CODIGOMESA = 999; - $item->DESCRICAO = 'TESTE'; - $item->ATIVO = 1; + $item->CODE = 999; + $item->DESCRIPTION = 'TEST'; + $item->ACTIVE = 1; - $result = $mysql->update('MESAS', $item, array('ID_MESA' => $ID_MESA), $ID_MESA); + $result = $mysql->update('BOARD', $item, array('ID_BOARD' => $ID_BOARD), $ID_BOARD); echo '
';
     echo print_r($result);
     echo '
'; /* delete */ - $ID_MESA = 531; - $result = $mysql->delete('MESAS', array('ID_MESA' => $ID_MESA)); + $ID_BOARD = 531; + $result = $mysql->delete('BOARD', array('ID_BOARD' => $ID_BOARD)); echo '
';
     echo print_r($result);
     echo '
'; /* execute */ - $sql = " INSERT INTO MESAS(ID_EMPRESA, CODIGOMESA, DESCRICAO) VALUES (2, 888, 'TESTE') "; + $sql = " INSERT INTO BOARD(CODE, DESCRIPTION) VALUES (888, 'TEST') "; $result = $mysql->execute($sql); echo '
';
     echo print_r($result);
@@ -97,4 +91,3 @@ try {
     die(print_r($e->getMessage().'-'.$mysql->getError()));
 }
 ```
-
diff --git a/sql/log.sql b/sql/log.sql
new file mode 100644
index 0000000..68568f0
--- /dev/null
+++ b/sql/log.sql
@@ -0,0 +1,7 @@
+CREATE TABLE IF NOT EXISTS `MYMYSQLLOG` (
+	`ID_MYMYSQLLOG` INT AUTO_INCREMENT,
+    `DATEHOUR` DATETIME DEFAULT CURRENT_TIMESTAMP(),
+    `LOG` VARCHAR(250),
+    `ERROR` VARCHAR(250),
+	CONSTRAINT PK_MYMYSQLLOG PRIMARY KEY (`ID_MYMYSQLLOG`)
+)ENGINE=INNODB;
diff --git a/src/MyMysql.php b/src/MyMysql.php
index 7416150..2874cf3 100755
--- a/src/MyMysql.php
+++ b/src/MyMysql.php
@@ -16,31 +16,38 @@
 
 class MyMysql
 {
-    private $DS = null; // DS
-    private $RT = null; // ROOT
-    private $DL = null; // DIR LOG
-
-    private $db = null;
-    private $error = '';
     private $ini = null;
+    private $dirlog = null;
+    private $db = null;
 
-    public function __construct($ini = array(), $dl = '')
+    public function __construct($ini = '', $dirlog = '')
     {
-        $this->DS = DIRECTORY_SEPARATOR;
-        $this->RT = realpath(dirname(__FILE__));
-        $this->DL = empty($dl) ? realpath(dirname(__FILE__)) : $dl;
+        $this->logger('MyMysql | method: __construct');
 
         $this->ini = $ini;
+        $this->dirlog = empty($dirlog) ? realpath(dirname(__FILE__)) : $dirlog;
+        $this->db = null;
+
+        if (empty($this->ini)) {
+            $err = "It's not possible to connect to the database because the parameters entered are invalid.";
+            $log = '';
+            $log .= 'Error. MyMysql | method: __construct.';
+
+            echo '
';
+            echo print_r($log);
+            echo print_r($err);
+            echo '
'; + die(); + } + $this->connection(); } - /* error */ - - public function getError() + public function __destruct() { - $this->logger('MyMysql | method: getError'); + $this->logger('MyMysql | method: __destruct'); - return $this->error; + $this->disconnect(); } /* connnect */ @@ -58,13 +65,6 @@ public function connection() return $this->db; } - public function isConnect() - { - $this->logger('MyMysql | method: isConnect'); - - return empty($this->db) ? false : true; - } - public function disconnect() { $this->logger('MyMysql | method: disconnect'); @@ -73,6 +73,13 @@ public function disconnect() return !$this->isConnect(); } + public function isConnect() + { + $this->logger('MyMysql | method: isConnect'); + + return empty($this->db) ? false : true; + } + /* fetch */ public function fetchRow($table, $where = array(), $orderBy = '') @@ -160,10 +167,10 @@ public function fetchAll2($sql, $where = array()) $log = $sql; - $connection = $this->db; - $stmt = $connection->prepare('SET SQL_BIG_SELECTS = 1'); + $conn = $this->db; + $stmt = $conn->prepare('SET SQL_BIG_SELECTS = 1'); $stmt->execute(); - $stmt = $connection->prepare($sql); + $stmt = $conn->prepare($sql); if (!empty($where)) { foreach ($where as $key => &$value) { $key = str_replace(':', '', $key); @@ -179,17 +186,18 @@ public function fetchAll2($sql, $where = array()) } /* - * BY BELUSSO: RETORNA 2, 3, 5 SELECTS NA MESMA PEGADA. - * NUM ARRAY, DE ACORDO COM A ORDEM DOS MESMOS + * RETURN ARRAY OF SELECT. */ public function fetchAll3($sql, $where = array()) { + $this->logger('MyMysql | method: fetchAll3'); + $log = $sql; - $connection = $this->db; - $stmt = $connection->prepare('SET SQL_BIG_SELECTS = 1'); + $conn = $this->db; + $stmt = $conn->prepare('SET SQL_BIG_SELECTS = 1'); $stmt->execute(); - $stmt = $connection->prepare($sql); + $stmt = $conn->prepare($sql); if (!empty($where)) { foreach ($where as $key => &$value) { $key = str_replace(':', '', $key); @@ -240,19 +248,14 @@ public function insert($table, $item) $this->logger($log); $exec = $stmt->execute(); - $this->error = ''; + $err = ''; if (!$exec) { $errorInfo = $stmt->errorInfo(); - $this->error = $errorInfo[1].' - '.$errorInfo[2]; + $err = $errorInfo[1].' - '.$errorInfo[2]; - $log = $this->error; - $this->logger($log); + $this->logger($log, $err); - echo '
';
-            echo print_r($log);
-            echo print_r($this->error);
-            echo '
'; - die(); + return false; } $item->id = $conn->lastInsertId(); $item->ID = $item->id; @@ -295,19 +298,14 @@ public function update($table, $item, $where, $id) $this->logger($log); $exec = $stmt->execute(); - $this->error = ''; + $err = ''; if (!$exec) { $errorInfo = $stmt->errorInfo(); - $this->error = $errorInfo[1].' - '.$errorInfo[2]; + $err = $errorInfo[1].' - '.$errorInfo[2]; - $log = $this->error; - $this->logger($log); + $this->logger($log, $err); - echo '
';
-            echo print_r($log);
-            echo print_r($this->error);
-            echo '
'; - die(); + return false; } $item->id = $id; $item->ID = $id; @@ -342,19 +340,14 @@ public function delete($table, $where) $this->logger($log); $exec = $stmt->execute(); - $this->error = ''; + $err = ''; if (!$exec) { $errorInfo = $stmt->errorInfo(); - $this->error = $errorInfo[1].' - '.$errorInfo[2]; + $err = $errorInfo[1].' - '.$errorInfo[2]; - $log = $this->error; - $this->logger($log); + $this->logger($log, $err); - echo '
';
-            echo print_r($log);
-            echo print_r($this->error);
-            echo '
'; - die(); + return false; } return $exec; @@ -366,8 +359,19 @@ public function execute($sql) $this->logger($sql); $stmt = $this->db->prepare($sql); + $exec = $stmt->execute(); - return $stmt->execute(); + $err = ''; + if (!$exec) { + $errorInfo = $stmt->errorInfo(); + $err = $errorInfo[1].' - '.$errorInfo[2]; + + $this->logger($log, $err); + + return false; + } + + return $exec; } public function sql($method = '', $sql = '', $table = '', $where = array(), $orderBy = '', $obj = null, $id = 0) @@ -431,22 +435,42 @@ public function rollback() private function logger($str, $err = '') { - if (true == $this->ini['DB_LOG']) { + if (true === $this->ini['DB_LOG'] || 'true' === $this->ini['DB_LOG'] || !empty($err)) { $date = date('Y-m-d'); $hour = date('H:i:s'); - @mkdir($this->DL, 0777, true); - @chmod($this->DL, 0777); + $isdb = false; + if (!empty($this->db)) { + $sql = " SELECT COUNT(*) AS CT + FROM information_schema.COLUMNS + WHERE TABLE_NAME = 'MYMYSQLLOG' "; - $log = ''; - $log .= "[$hour] > $str \n"; - if (!empty($err)) { - $log .= "[ERROR] > $err \n\n"; + $row = $this->fetchRow2($sql); + + if (!empty($row) && $row->CT > 0) { + $obj = new stdClass(); + $obj->LOG = "[$hour] > $str"; + $obj->ERROR = "[ERROR] > $err"; + + $this->insert('MYMYSQLLOG', $obj); + $isdb = true; + } } - $file = fopen($this->DL.$this->DS."log-$date.txt", 'a+'); - fwrite($file, $log); - fclose($file); + if (false === $isdb) { + @mkdir($this->dirlog, 0777, true); + @chmod($this->dirlog, 0777); + + $log = ''; + $log .= "[$hour] > $str \n"; + if (!empty($err)) { + $log .= '[ERROR] > '.$err." \n\n"; + } + + $file = @fopen($this->dirlog.DIRECTORY_SEPARATOR."log-$date.txt", 'a+'); + @fwrite($file, $log); + @fclose($file); + } } } diff --git a/src/MySql.php b/src/MySql.php deleted file mode 100755 index 4855cf9..0000000 --- a/src/MySql.php +++ /dev/null @@ -1,470 +0,0 @@ -ini = null; - $this->db = null; - $this->error = ''; - - $this->loadIni(); - } - - public function loadIni() - { - $this->ini = parse_ini_file(CONFIG.DS.'application.ini'); - } - - /* error */ - - public function getError() - { - $this->logger('MyMysql | method: getError'); - - return $this->error; - } - - /* connnect */ - - public function connection() - { - $this->logger('MyMysql | method: connection'); - - if (!empty($this->db)) { - return $this->db; - } - - $this->db = new PDO('mysql:host='.$this->ini['DB_HOST'].';dbname='.$this->ini['DB_NAME'], $this->ini['DB_USER'], $this->ini['DB_PASS'], array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')); - - // For Amazon. - $stmt = $this->db->prepare("SET time_zone = 'America/Montevideo'"); - $stmt->execute(); - - return $this->db; - } - - public function isConnect() - { - $this->logger('MyMysql | method: isConnect'); - - return empty($this->db) ? false : true; - } - - public function disconnect() - { - $this->logger('MyMysql | method: disconnect'); - $this->db = null; - - return !$this->isConnect(); - } - - /* fetch */ - - public function fetchRow($table, $where = array(), $orderBy = '') - { - $this->logger('MyMysql | method: fetchRow'); - - $sql = " SELECT * FROM $table WHERE 1 = 1 "; - if (!empty($where)) { - foreach ($where as $key => $value) { - $key = str_replace(':', '', $key); - $sql .= " AND $key = :$key "; - } - } - $sql .= $orderBy; - $log = $sql; - - $stmt = $this->db->prepare($sql); - if (!empty($where)) { - foreach ($where as $key => &$value) { - $key = str_replace(':', '', $key); - $stmt->bindParam($key, $value); - $log = preg_replace('/:'.$key.'\b/i', "'$value'", $log); - } - } - - $this->logger($log); - $exec = $stmt->execute(); - - return (!$exec) ? false : $stmt->fetchObject(); - } - - public function fetchRow2($sql, $where = array()) - { - $this->logger('MyMysql | method: fetchRow2'); - - $log = $sql; - - $stmt = $this->db->prepare($sql); - if (!empty($where)) { - foreach ($where as $key => &$value) { - $key = str_replace(':', '', $key); - $stmt->bindParam($key, $value); - $log = preg_replace('/:'.$key.'\b/i', "'$value'", $log); - } - } - - $this->logger($log); - $exec = $stmt->execute(); - - return (!$exec) ? false : $stmt->fetchObject(); - } - - public function fetchAll($table, $where = array(), $orderBy = '') - { - $this->logger('MyMysql | method: fetchAll'); - - $sql = " SELECT * FROM $table WHERE 1 = 1 "; - if (!empty($where)) { - foreach ($where as $key => $value) { - $key = str_replace(':', '', $key); - $sql .= " AND $key = :$key "; - } - } - $sql .= $orderBy; - $log = $sql; - - $stmt = $this->db->prepare($sql); - if (!empty($where)) { - foreach ($where as $key => &$value) { - $key = str_replace(':', '', $key); - $stmt->bindParam($key, $value); - $log = preg_replace('/:'.$key.'\b/i', "'$value'", $log); - } - } - - $this->logger($log); - $exec = $stmt->execute(); - - return (!$exec) ? false : $stmt->fetchAll(PDO::FETCH_OBJ); - } - - public function fetchAll2($sql, $where = array()) - { - $this->logger('MyMysql | method: fetchAll2'); - - $log = $sql; - - $connection = $this->db; - $stmt = $connection->prepare('SET SQL_BIG_SELECTS = 1'); - $stmt->execute(); - $stmt = $connection->prepare($sql); - if (!empty($where)) { - foreach ($where as $key => &$value) { - $key = str_replace(':', '', $key); - $stmt->bindParam($key, $value); - $log = preg_replace('/:'.$key.'\b/i', "'$value'", $log); - } - } - - $this->logger($log); - $exec = $stmt->execute(); - - return (!$exec) ? false : $stmt->fetchAll(PDO::FETCH_OBJ); - } - - /* - * BY BELUSSO: RETORNA 2, 3, 5 SELECTS NA MESMA PEGADA. - * NUM ARRAY, DE ACORDO COM A ORDEM DOS MESMOS - */ - public function fetchAll3($sql, $where = array()) - { - $log = $sql; - - $connection = $this->db; - $stmt = $connection->prepare('SET SQL_BIG_SELECTS = 1'); - $stmt->execute(); - $stmt = $connection->prepare($sql); - if (!empty($where)) { - foreach ($where as $key => &$value) { - $key = str_replace(':', '', $key); - $stmt->bindParam($key, $value); - $log = preg_replace('/:'.$key.'\b/i', "'$value'", $log); - } - } - - $this->logger($log); - $exec = $stmt->execute(); - $results = array(); - - do { - $rowset = $stmt->fetchAll(PDO::FETCH_OBJ); - $results[] = $rowset ?? array(); - } while ($stmt->nextRowset()); - - return $results; - } - - public function insert($table, $item) - { - $this->logger('MyMysql | method: insert'); - - $this->deleteColumnFromSqlIfNotExist($table, $item); - - $sql = ''; - $sql .= " INSERT INTO $table ("; - foreach ($item as $key => $value) { - $sql .= "$key,"; - } - $sql = rtrim($sql, ','); - $sql .= ') VALUES ('; - foreach ($item as $key => $value) { - $sql .= ":$key,"; - } - $sql = rtrim($sql, ','); - $sql .= ')'; - $log = $sql; - - $db = $this->db; - $stmt = $db->prepare($sql); - foreach ($item as $key => &$value) { - $stmt->bindParam($key, $value); - $log = preg_replace('/:'.$key.'\b/i', "'$value'", $log); - } - - $this->logger($log); - $exec = $stmt->execute(); - - $this->error = ''; - if (!$exec) { - $errorInfo = $stmt->errorInfo(); - $this->error = $errorInfo[1].' - '.$errorInfo[2]; - - $log = $this->error; - $this->logger($log); - - echo '
';
-            echo print_r($log);
-            echo print_r($this->error);
-            echo '
'; - die(); - } - $item->id = $db->lastInsertId(); - $item->ID = $item->id; - - return (!$exec) ? false : $item; - } - - public function update($table, $item, $where, $id) - { - $this->logger('MyMysql | method: update'); - - $this->deleteColumnFromSqlIfNotExist($table, $item); - - $sql = ''; - $sql .= " UPDATE $table SET "; - foreach ($item as $key => $value) { - $sql .= "$key=:$key,"; - } - $sql = rtrim($sql, ','); - $sql .= ' WHERE 1 = 1 '; - foreach ($where as $key => $value) { - $key = str_replace(':', '', $key); - $sql .= " AND $key = :$key "; - } - $log = $sql; - - $db = $this->db; - $stmt = $db->prepare($sql); - foreach ($item as $key => &$value) { - $key = str_replace(':', '', $key); - $stmt->bindParam($key, $value); - $log = preg_replace('/:'.$key.'\b/i', "'$value'", $log); - } - foreach ($where as $key => &$value) { - $key = str_replace(':', '', $key); - $stmt->bindParam($key, $value); - $log = preg_replace('/:'.$key.'\b/i', "'$value'", $log); - } - - $this->logger($log); - $exec = $stmt->execute(); - - $this->error = ''; - if (!$exec) { - $errorInfo = $stmt->errorInfo(); - $this->error = $errorInfo[1].' - '.$errorInfo[2]; - - $log = $this->error; - $this->logger($log); - - echo '
';
-            echo print_r($log);
-            echo print_r($this->error);
-            echo '
'; - die(); - } - $item->id = $id; - $item->ID = $id; - - return (!$exec) ? false : $item; - } - - public function delete($table, $where) - { - $this->logger('MyMysql | method: delete'); - - if (empty($where)) { - $this->logger('Impossible to delete without the clause where...'); - - return false; - } - - $sql = "DELETE FROM $table WHERE 1 = 1 "; - foreach ($where as $key => $value) { - $key = str_replace(':', '', $key); - $sql .= " AND $key = :$key "; - } - $log = $sql; - - $stmt = $this->db->prepare($sql); - foreach ($where as $key => &$value) { - $key = str_replace(':', '', $key); - $stmt->bindParam($key, $value); - $log = preg_replace('/:'.$key.'\b/i', "'$value'", $log); - } - - $this->logger($log); - $exec = $stmt->execute(); - - $this->error = ''; - if (!$exec) { - $errorInfo = $stmt->errorInfo(); - $this->error = $errorInfo[1].' - '.$errorInfo[2]; - - $log = $this->error; - $this->logger($log); - - echo '
';
-            echo print_r($log);
-            echo print_r($this->error);
-            echo '
'; - die(); - } - - return $exec; - } - - public function execute($sql) - { - $this->logger('MyMysql | method: execute'); - $this->logger($sql); - - $stmt = $this->db->prepare($sql); - - return $stmt->execute(); - } - - public function sql($method = '', $sql = '', $table = '', $where = array(), $orderBy = '', $obj = null, $id = 0) - { - $this->logger('MyMysql | method: sql'); - - $result = new stdClass(); - $result->msg = ''; - $result->status = true; - $result->model = null; - - if ('fetchRow' === $method) { - $result->model = $this->fetchRow($table, $where, $orderBy); - } elseif ('fetchAll' === $method) { - $result->model = $this->fetchAll($table, $where, $orderBy); - } elseif ('fetchRow2' === $method) { - $result->model = $this->fetchRow2($sql); - } elseif ('fetchAll2' === $method) { - $result->model = $this->fetchAll2($sql); - } elseif ('insert' === $method) { - $result->model = $this->insert($table, $obj); - } elseif ('update' === $method) { - $result->model = $this->update($table, $obj, $where, $id); - } elseif ('delete' === $method) { - $result->model = $this->delete($table, $where); - } else { - $result->status = false; - } - - if (is_bool($result->model) && (false == $result->model)) { - $result->status = false; - $result->msg = "Ops. Ocorreu um erro. Method: $method. Sql: $sql. Table: $table. Where: ".json_encode($where).". Order By: $orderBy. Obj: ".json_encode($obj).". Id: $id "; - } - - return $result; - } - - /* transaction */ - - public function beginTransaction() - { - return $this->db->beginTransaction(); - } - - public function closeTransaction() - { - return $this->db->closeTransaction(); - } - - public function commit() - { - return $this->db->commit(); - } - - public function rollback() - { - return $this->db->rollback(); - } - - /* private */ - - private function logger($msg) - { - if (true == $this->ini['DB_LOG']) { - $path = LOG.DS; - $file = date('Y-m-d').'.log'; - - @mkdir($path, 0777, true); - @chmod($path, 0777); - - $file = @fopen($path.$file, 'a+'); - fwrite($file, $msg); - fwrite($file, "\n"); - fclose($file); - } - } - - /* private func */ - - private function deleteColumnFromSqlIfNotExist($table, &$item) - { - $sql = " SELECT COLUMN_NAME - FROM information_schema.COLUMNS - WHERE TABLE_NAME = '$table' "; - - $stmt = $this->db->prepare($sql); - $exec = $stmt->execute(); - - $arr = (!$exec) ? false : $stmt->fetchAll(PDO::FETCH_OBJ); - - if (!empty($arr)) { - $columns = array(); - foreach ($arr as $key => $value) { - $columns[] = $value->COLUMN_NAME; - } - - foreach ($item as $key => $value) { - if (!in_array($key, $columns)) { - unset($item->$key); - } - } - } - } -} From dca1fe35ee2bbd623404c448a9f9dd28c72bbab8 Mon Sep 17 00:00:00 2001 From: Eduardo Malherbi Date: Fri, 30 Apr 2021 17:44:46 -0300 Subject: [PATCH 3/5] continua --- src/MyMysql.php | 60 +++++++++++++++++++++++-------------------------- 1 file changed, 28 insertions(+), 32 deletions(-) diff --git a/src/MyMysql.php b/src/MyMysql.php index 2874cf3..0c0fa34 100755 --- a/src/MyMysql.php +++ b/src/MyMysql.php @@ -22,16 +22,15 @@ class MyMysql public function __construct($ini = '', $dirlog = '') { - $this->logger('MyMysql | method: __construct'); - $this->ini = $ini; $this->dirlog = empty($dirlog) ? realpath(dirname(__FILE__)) : $dirlog; $this->db = null; + $this->logger('MyMysql | method: __construct'); + if (empty($this->ini)) { $err = "It's not possible to connect to the database because the parameters entered are invalid."; - $log = ''; - $log .= 'Error. MyMysql | method: __construct.'; + $log = 'Error. MyMysql | method: __construct.'; echo '
';
             echo print_r($log);
@@ -435,42 +434,39 @@ public function rollback()
 
     private function logger($str, $err = '')
     {
-        if (true === $this->ini['DB_LOG'] || 'true' === $this->ini['DB_LOG'] || !empty($err)) {
-            $date = date('Y-m-d');
-            $hour = date('H:i:s');
+        $date = date('Y-m-d');
+        $hour = date('H:i:s');
 
-            $isdb = false;
-            if (!empty($this->db)) {
-                $sql = " SELECT COUNT(*) AS CT
-                    FROM information_schema.COLUMNS
-                    WHERE TABLE_NAME = 'MYMYSQLLOG' ";
+        if (!empty($err) && !empty($this->db)) {
+            $sql = " SELECT COUNT(*) AS CT
+                FROM information_schema.COLUMNS
+                WHERE TABLE_NAME = 'MYMYSQLLOG' ";
 
-                $row = $this->fetchRow2($sql);
+            $row = $this->fetchRow2($sql);
 
-                if (!empty($row) && $row->CT > 0) {
-                    $obj = new stdClass();
-                    $obj->LOG = "[$hour] > $str";
-                    $obj->ERROR = "[ERROR] > $err";
+            if (!empty($row) && $row->CT > 0) {
+                $obj = new stdClass();
+                $obj->LOG = "[$hour] > $str";
+                $obj->ERROR = "[ERROR] > $err";
 
-                    $this->insert('MYMYSQLLOG', $obj);
-                    $isdb = true;
-                }
+                $this->insert('MYMYSQLLOG', $obj);
+                $isdb = true;
             }
+        }
 
-            if (false === $isdb) {
-                @mkdir($this->dirlog, 0777, true);
-                @chmod($this->dirlog, 0777);
-
-                $log = '';
-                $log .= "[$hour] > $str \n";
-                if (!empty($err)) {
-                    $log .= '[ERROR] > '.$err." \n\n";
-                }
+        if (true === $this->ini['DB_LOG'] || 'true' === $this->ini['DB_LOG']) {
+            @mkdir($this->dirlog, 0777, true);
+            @chmod($this->dirlog, 0777);
 
-                $file = @fopen($this->dirlog.DIRECTORY_SEPARATOR."log-$date.txt", 'a+');
-                @fwrite($file, $log);
-                @fclose($file);
+            $log = '';
+            $log .= "[$hour] > $str \n";
+            if (!empty($err)) {
+                $log .= '[ERROR] > '.$err." \n\n";
             }
+
+            $file = @fopen($this->dirlog.DIRECTORY_SEPARATOR."log-$date.txt", 'a+');
+            @fwrite($file, $log);
+            @fclose($file);
         }
     }
 

From afee96f4c6e5502a2d78e6f8ca9f4180715967f9 Mon Sep 17 00:00:00 2001
From: Eduardo Malherbi 
Date: Mon, 3 May 2021 09:08:26 -0300
Subject: [PATCH 4/5] ajustes

---
 src/MyMysql.php | 2 --
 1 file changed, 2 deletions(-)

diff --git a/src/MyMysql.php b/src/MyMysql.php
index 0c0fa34..295a0dd 100755
--- a/src/MyMysql.php
+++ b/src/MyMysql.php
@@ -441,7 +441,6 @@ private function logger($str, $err = '')
             $sql = " SELECT COUNT(*) AS CT
                 FROM information_schema.COLUMNS
                 WHERE TABLE_NAME = 'MYMYSQLLOG' ";
-
             $row = $this->fetchRow2($sql);
 
             if (!empty($row) && $row->CT > 0) {
@@ -450,7 +449,6 @@ private function logger($str, $err = '')
                 $obj->ERROR = "[ERROR] > $err";
 
                 $this->insert('MYMYSQLLOG', $obj);
-                $isdb = true;
             }
         }
 

From 0ce778e586ade2d3675d79782a16f721962690bf Mon Sep 17 00:00:00 2001
From: Eduardo Malherbi 
Date: Mon, 3 May 2021 19:53:56 -0300
Subject: [PATCH 5/5] update

---
 src/MyMysql.php | 1 +
 1 file changed, 1 insertion(+)

diff --git a/src/MyMysql.php b/src/MyMysql.php
index 295a0dd..f3f799b 100755
--- a/src/MyMysql.php
+++ b/src/MyMysql.php
@@ -441,6 +441,7 @@ private function logger($str, $err = '')
             $sql = " SELECT COUNT(*) AS CT
                 FROM information_schema.COLUMNS
                 WHERE TABLE_NAME = 'MYMYSQLLOG' ";
+
             $row = $this->fetchRow2($sql);
 
             if (!empty($row) && $row->CT > 0) {