123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174 |
- <?php
-
- namespace SCF\Core;
-
- use PDO;
- use PDOException;
-
- class Database {
- /**
- * @var null|PDO
- */
- private $db = NULL;
-
- /**
- * @var
- */
- private $stmt;
-
- /**
- * @var string
- */
- private $error;
- /**
- * @var int
- */
- private $queryCounter = 0;
-
- /**
- * @var array
- */
- private $sqlQueries = [];
-
- /**
- * Database constructor.
- * @param $dbext
- * @param $dbhost
- * @param $dbuser
- * @param $dbpass
- * @param $dbname
- */
- public function __construct($dbext, $dbhost, $dbuser, $dbpass, $dbname)
- {
- $dsn = $dbext.':dbname='.$dbname.';host='.$dbhost.';charset=utf8';
-
- $options = [
- PDO::ATTR_PERSISTENT => true,
- PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
- ];
-
- try {
- $this->db = new PDO($dsn, $dbuser, $dbpass, $options);
- }
- catch (PDOException $e) {
- $this->error = $e->getMessage();
- }
- }
-
- /**
- * @param $query
- */
- public function query($query)
- {
- $this->stmt = $this->db->prepare($query);
- $this->queryCounter++;
- $this->setSqlQueries($query);
-
- }
-
- /**
- * @param $param
- * @param $value
- * @param null $type
- */
- public function bind($param, $value, $type = null)
- {
- if(is_null($type)) {
- switch(true) {
- case is_int($value):
- $type = PDO::PARAM_INT;
- break;
- case is_bool($value):
- $type = PDO::PARAM_BOOL;
- break;
- case is_null($value):
- $type = PDO::PARAM_NULL;
- break;
- default:
- $type = PDO::PARAM_STR;
- }
- }
-
- $this->stmt->bindValue($param,$value,$type);
- }
-
- /**
- * @return mixed
- */
- public function execute()
- {
- try {
- return $this->stmt->execute();
- }
- catch (PDOException $e) {
- $this->error = $e->getMessage();
- }
- }
-
- /**
- * @return mixed
- */
- public function fetchArray()
- {
- $this->execute();
- return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
- }
-
- /**
- * @return mixed
- */
- public function single()
- {
- $this->execute();
- return $this->stmt->fetch(PDO::FETCH_ASSOC);
- }
-
- /**
- * @return mixed
- */
- public function rowCount()
- {
- return $this->stmt->rowCount();
- }
-
- /**
- * @return mixed
- */
- public function lastInsertId()
- {
- return $this->stmt->lastInsertId();
- }
-
- /**
- * @return string
- */
- public function getError()
- {
- return $this->error;
- }
-
- /**
- * @return int
- */
- public function getQueryCounter()
- {
- return $this->queryCounter;
- }
-
- /**
- * @param array $sqlQueries
- */
- public function setSqlQueries($sqlQueries)
- {
- $this->sqlQueries[] = $sqlQueries;
- }
-
- /**
- * @return array
- */
- public function getSqlQueries()
- {
- return $this->sqlQueries;
- }
-
- }
|