Exemple #1
0
 /**
  * DbWorker constructor.
  * @param $dsn
  * @param null $user
  * @param null $password
  * @param null $options
  */
 public function __construct($dsn, $user = null, $password = null, $options = null)
 {
     try {
         parent::__construct($dsn, $user, $password, null);
         $this->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
         $this->exec("set names utf8");
     } catch (\PDOException $e) {
         echo 'Connection failed: ' . $e->getMessage();
         Log::write('Connection failed: ' . $e->getMessage(), Log::TYPE_ERROR);
         exit;
     }
 }
 /**
  * @param Query $query
  * @param bool|true $fetchAll
  * @return array|mixed
  * @throws \Exception
  */
 public final function query(Query $query, $fetchAll = true)
 {
     $params = [];
     $sql = 'SELECT ';
     if ($fetchAll == false) {
         $query->limit = 1;
     }
     /** Fields */
     if (is_array($query->select) && count($query->select)) {
         $sql .= implode(', ', $query->select);
     } else {
         if (strlen($query->select)) {
             $sql .= $query->select;
         } else {
             $sql .= '*';
         }
     }
     $sql .= ' FROM ' . $this->table . ' AS t ';
     if (strlen($query->join)) {
         $sql .= $query->join;
     }
     if (count($query->where) || count($this->selectedScopes)) {
         $where = [];
         foreach ($query->where as $item) {
             $where[] = $item[0] . ' ' . $item[1] . ' ?';
             $params[] = $item[2];
         }
         foreach ($this->selectedScopes as $item) {
             $where[] = $this->scopes[$item];
         }
         $sql .= ' WHERE ' . implode(' AND ', $where);
     }
     if (strlen($query->group)) {
         $sql .= ' GROUP BY ' . $query->group;
     }
     if (strlen($query->order)) {
         $sql .= ' ORDER BY ' . $query->order;
     }
     if ($query->limit > 0) {
         $sql .= ' LIMIT ' . $query->limit . ';';
     }
     $statement = Micro::$app->db->prepare($sql);
     if (Micro::$app->config['db']['verbose'] == true) {
         Log::write('SQL: ' . $sql . (count($params) ? ' Params: ' . join('; ', $params) . '.' : ''), Log::TYPE_VERBOSE);
     }
     try {
         $statement->execute($params);
     } catch (\Exception $e) {
         print 'Error: ' . $e . "<br>\n";
         print 'SQL: ' . $sql . "<br>\n";
         Log::write($e, Log::TYPE_ERROR);
         throw $e;
     }
     if ($fetchAll) {
         $results = $statement->fetchAll(\PDO::FETCH_CLASS, get_called_class());
         array_walk($results, function (&$item) {
             $item->isNewRecord = false;
         });
         return $results;
     } else {
         $result = $statement->fetchObject(get_called_class());
         if ($result != null) {
             $result->isNewRecord = false;
         }
         return $result;
     }
 }