Exemplo n.º 1
0
 function getDb()
 {
     if (!$this->_db) {
         $dsn = array();
         $dsn['scheme'] = 'mysql';
         $dsn['path'] = $this->getConfig('db');
         if ($this->getConfig('other_db') == "1") {
             $dsn = array_merge($dsn, array('host' => $this->getConfig('host'), 'user' => $this->getConfig('user'), 'pass' => $this->getConfig('pass')));
         } else {
             $appOptions = $this->getDi()->getParameters();
             $dbConfig = $appOptions['db']['mysql'];
             $dsn = array_merge($dsn, array('host' => $dbConfig['host'], 'user' => $dbConfig['user'], 'pass' => $dbConfig['pass']));
             if (isset($dbConfig['port']) && $dbConfig['port']) {
                 $dsn['port'] = $dbConfig['port'];
             }
         }
         if ($dsn['host'] && strpos($dsn['host'], ':') !== false && preg_match('/\\:(\\d+)$/', $dsn['host'])) {
             list($dsn['host'], $dsn['port']) = explode(':', $dsn['host']);
         }
         $this->_db = Am_Db::connect($dsn, true);
         $this->_db->setErrorHandler(array($this, 'dbErrorHandler'));
         $this->_db->setIdentPrefix($this->getConfig('prefix'));
         $this->_db->query("USE ?#", $dsn['path']);
         $this->_db->query("SET NAMES utf8");
         $this->_db->query("SET SESSION sql_mode=''");
     }
     if ($this->sqlDebug) {
         if (!empty($this->getDi()->db->_logger)) {
             $this->_db->setLogger($this->getDi()->db->_logger);
         }
     }
     return $this->_db;
 }
Exemplo n.º 2
0
 function getDb()
 {
     if (!$this->_db) {
         $dsn = array();
         $dsn['scheme'] = 'mysql';
         $dsn['path'] = $this->getConfig('db');
         if ($this->getConfig('other_db') == "1") {
             $dsn = array_merge($dsn, array('host' => $this->getConfig('host'), 'user' => $this->getConfig('user'), 'pass' => $this->getConfig('pass')));
         } else {
             $appOptions = $this->getDi()->getParameters();
             $dbConfig = $appOptions['db']['mysql'];
             $dsn = array_merge($dsn, array('host' => $dbConfig['host'], 'user' => $dbConfig['user'], 'pass' => $dbConfig['pass']));
         }
         $this->_db = Am_Db::connect($dsn, true);
         $this->_db->setErrorHandler(array($this, 'dbErrorHandler'));
         $this->_db->setIdentPrefix($this->getConfig('prefix'));
         $this->_db->query("USE ?#", $dsn['path']);
     }
     if ($this->sqlDebug) {
         if (!empty($this->getDi()->db->_logger)) {
             $this->_db->setLogger($this->getDi()->db->_logger);
         }
     }
     return $this->_db;
 }
Exemplo n.º 3
0
 /**
  * возвращает массив. 1ый элемент - сериализуемая строка. 2ой айди валюты по умолчанию
  * @return array mixed
  */
 function getCur()
 {
     $sql = "SELECT user_currency_list AS li, user_currency_default AS def FROM users WHERE id = ?";
     $li = $this->db->query($sql, $this->getId());
     $a = $li[0];
     return $a;
 }
Exemplo n.º 4
0
 /**
  * Удаляет выбранную категорию (и все подкатегории, если это родительская категория)
  * @param int $id
  * @return array
  */
 function del($id = 0)
 {
     $now = date('Y-m-d H:i:s');
     // Удаляет (скрывает) категорию, заодно и дочерние (если есть)
     $sql = "\n            UPDATE category\n                SET updated_at=?, deleted_at=?\n            WHERE\n                    user_id=?\n                AND (cat_id=? OR cat_parent=?)\n        ";
     $this->db->query($sql, $now, $now, Core::getInstance()->user->getId(), $id, $id);
     //@FIXME Починить удаление операций по категории
     Core::getInstance()->user->initUserCategory();
     Core::getInstance()->user->save();
     return array('result' => array('text' => 'Категория успешно удалена'));
 }
 /**
  * Удаляет все операции по указанной категории
  *
  * @param oldUser $user
  * @param int $catId
  */
 function deleteOperationsByCategory(oldUser $user, $catId)
 {
     $sql = "SELECT id FROM operation WHERE user_id = ? AND cat_id = ?";
     $operations = $this->db->selectCol($sql, $user->getId(), $catId);
     if (count($operations) > 0) {
         $this->db->query("BEGIN;");
         foreach ($operations as $opId) {
             $this->deleteOperation($opId);
         }
         $this->db->query("COMMIT;");
     }
     return (int) count($operations);
 }
Exemplo n.º 6
0
 /**
  * Удаляет тег
  * @param string $tag
  * @return json
  */
 function del($tag = '')
 {
     if (empty($tag)) {
         $this->errors[] = 'Тег не должен быть пустым';
         return false;
     }
     $sql = "DELETE FROM tags WHERE name=? AND user_id=?";
     $this->db->query($sql, $tag, Core::getInstance()->user->getId());
     $sql = "UPDATE operation o SET tags = REPLACE(tags, ?, '') WHERE user_id=?";
     $this->db->query($sql, $tag, Core::getInstance()->user->getId());
     Core::getInstance()->user->initUserTags();
     Core::getInstance()->user->save();
     return Core::getInstance()->user->getUserTags();
 }
Exemplo n.º 7
0
 /**
  * Сравнение расходов за периоды, Сравнение доходов за периоды
  *
  * @param int               $type           Тип операции. 0 - Расход, 1 - Доход
  * @param string mysqldate  $date1          Дата начала первого периода в формате "YYYY-MM-DD"
  * @param string mysql date $date2          Дата окончания первого периода в формате "YYYY-MM-DD"
  * @param string mysql date $date3          Дата начала второго периода в формате "YYYY-MM-DD"
  * @param string mysql date $date4          Дата окончания второго периода в формате "YYYY-MM-DD"
  * @param int | string      $accounts       Счёт в виде числа, или несколько чисел разделённых запятой
  * @param int               $currencyId     Ид валюты в которой выводить результат
  * @return array
  */
 function CompareForPeriods($type, $date1 = '', $date2 = '', $date3 = '', $date4 = '', $accounts = '', $currencyId = 0)
 {
     $queryString = "SELECT\n                    c.cat_name,\n                    c.cat_id,\n                    a.account_currency_id as cur_id,\n                    sum(abs(op.money)) as su,\n                    p.per\n                FROM operation op\n                INNER JOIN accounts a\n                    ON a.account_id=op.account_id\n                INNER JOIN category c\n                    ON c.cat_id=op.cat_id\n                INNER JOIN (\n                        SELECT ? AS begin_date, ? AS end_date, 1 AS per\n                        UNION ALL\n                        SELECT ? AS begin_date, ? AS end_date, 2 AS per\n                    ) p\n                    ON op.date between p.begin_date AND p.end_date\n                WHERE\n                    op.`type`= ?\n                    AND op.user_id= ? AND op.accepted=1\n                    AND op.deleted_at IS NULL\n                    AND a.deleted_at IS NULL\n                    AND c.deleted_at IS NULL\n                    AND a.account_id IN({$accounts})\n                GROUP BY c.cat_id, a.account_currency_id, p.per";
     $rows = $this->_db->query($queryString, $date1, $date2, $date3, $date4, $type, $this->_user->getId());
     $result = array();
     foreach ($rows as $value) {
         $money = new myMoney(abs($value['su']), $value['cur_id']);
         $tempId = $value['per'] . $value['cat_id'];
         $result[$tempId] = $value;
         unset($result[$tempId]['cur_id']);
         unset($result[$tempId]['su']);
         if (isset($result[$tempId]['su'])) {
             $result[$tempId]['su'] += $this->ex->convert($money, $currencyId)->getAmount();
         } else {
             $result[$tempId]['su'] = $this->ex->convert($money, $currencyId)->getAmount();
         }
     }
     return array($result);
 }
Exemplo n.º 8
0
 function apply(DbSimple_Mysql $db)
 {
     $prefix = $db->getPrefix();
     foreach ($this->getSql($prefix) as $sql) {
         $db->query($sql);
     }
 }
Exemplo n.º 9
0
 public function delete($key)
 {
     if (!$key) {
         throw new Am_Exception_Db("key is empty in " . get_class($this) . "->delete()");
     }
     $this->_db->query("DELETE FROM {$this->_table} WHERE ?#=?", $this->_key, $key);
     if ($this->cache) {
         unset($this->cache[$key]);
     }
 }
Exemplo n.º 10
0
 public function write($id, $data)
 {
     $row = array('id' => $id, 'modified' => Am_Di::getInstance()->time, 'lifetime' => $this->getLifetime(), 'user_id' => null, 'data' => $data);
     $this->db->query("REPLACE INTO ?_session SET ?a", $row);
     return true;
 }
Exemplo n.º 11
0
 /**
  * TearDown
  */
 protected final function tearDown()
 {
     $this->_end();
     $this->db->query("ROLLBACK");
 }
Exemplo n.º 12
0
 /**
  * Удаляет операцию финансовой цели
  * @param $tar_oper_id int Ид операции
  * @param $tr_id int Ид финансовой цели
  * @return bool
  */
 public function delTargetOperation($tar_oper_id = 0, $tr_id = 0)
 {
     $this->db->query("DELETE FROM target_bill WHERE user_id=? AND id=?;", Core::getInstance()->user->getId(), $tar_oper_id);
     return $this->staticTargetUpdate($tr_id);
 }
Exemplo n.º 13
0
 function deleteRecord($ip)
 {
     $this->db->query("DELETE FROM ?_failed_login\n            WHERE ip=? AND login_type=?", $ip, $this->loginType);
 }
Exemplo n.º 14
0
 public function subscribe($spamer)
 {
     $sql = "UPDATE users SET getNotify=? WHERE id=? ;";
     return $this->db->query($sql, $spamer, $this->user_id);
 }