query() public method

Generates and executes SQL query.
public query ( $sql, $params ) : ResultSet
return ResultSet
コード例 #1
0
ファイル: CliInstall.php プロジェクト: trejjam/emailing
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->database->query($this->getFile(self::FILE_EMAILS_TABLE));
     $this->database->query($this->getFile(self::FILE_GROUPS_TABLE));
     $this->database->query($this->getFile(self::FILE_SENDER_LIST_TABLE));
     $this->database->query($this->getFile(self::FILE_GROUP_EMAIL_TABLE));
 }
コード例 #2
0
 public function renderDefault()
 {
     // 1. Vlozeni noveho zaznamu do tabulky se zavody
     // 2. Vyber zavodu (identifikatoru), vetsinou toho, ktery byl vytvoren v predchozim bode
     $id_event = "VCHOD2015";
     // 3. Kontrola identifikatoru zavodu - nesmi byt pouzit v tabulce casu
     $data = $this->database->query('select id from sm_time where id_event = ?', $id_event);
     if ($data->getRowCount() > 0) {
         // Chyba! Vyzadovat novou volbu zavodu
         // Pozor! VCHOD2015 j*z v tabulce casu je!
     }
     // 4. Zadani textoveho souboru s vysledky s predepsanym DR
     //        $input_file = "/home/vencs88/php/import_time/data/cp_praha2015.txt";
     //        $input_file = "/home/vencs88/php/import_time/data/vysledky_blbec.txt";
     $input_file = "/home/vencs88/php/import_time/data/mem2015.txt";
     // 5. Vizualni kontrola chyb po nacteni vysledku do pomocne tabulky
     $this->template->status = $this->importTimeManager->getImportData($input_file, $id_event);
     $this->template->data = $this->database->table('sm_import');
     // 6. Nejsou-li chyby, umoznit import vysledku do tabulky casu
     //        INSERT INTO sm_time
     //            (
     //                id_stroke,
     //                id_swimmer,
     //                time,
     //                rank,
     //                point
     //            )
     //            SELECT * FROM sm_import;
     //
     //        // Zvazit vymaz pomocne tabulky
     //        DELETE FROM sm_import;
 }
コード例 #3
0
ファイル: Uzivatele.php プロジェクト: stanley89/piratskelisty
 public function setRole($id, $roles)
 {
     $this->database->query("DELETE FROM uzivatele_role WHERE uzivatel_id=?;", $id);
     foreach ($roles as $k => $v) {
         if ($v == 1) {
             $this->database->query("INSERT INTO uzivatele_role ", array("role_id" => $k, "uzivatel_id" => $id));
         }
     }
 }
コード例 #4
0
ファイル: Upload.php プロジェクト: stanley89/piratskelisty
 public function save($vals)
 {
     $arr = array('alt' => $vals['alt'], 'title' => $vals['title']);
     if (!empty($vals['id'])) {
         $this->database->query("UPDATE upload SET ", $arr, " WHERE id=?;", $vals['id']);
         return $this->get($vals['id']);
     } else {
         $arr['extension'] = $vals['extension'];
         $this->database->query("INSERT INTO upload ", $arr);
         return $this->get($this->database->getInsertId());
     }
 }
コード例 #5
0
ファイル: BasePresenter.php プロジェクト: vitush93/dba
 protected function startup()
 {
     parent::startup();
     $this->database->query("SET search_path TO dba");
     // TODO temporary schema search path fix
     if ($this->presenter->name != 'Sign' && !$this->user->isLoggedIn()) {
         $this->redirect('Sign:in');
     }
     if ($this->user->getLogoutReason() == Nette\Security\IUserStorage::INACTIVITY) {
         $this->flashMessage('You have been logged out (20 minutes).', 'info');
     }
 }
コード例 #6
0
ファイル: ApikeyRepository.php プロジェクト: pogodi/Scud
 /**
  * @param $application
  * @param $key
  * @return false|Apikey
  */
 public function getKey($application, $key)
 {
     $row = $this->database->query("SELECT * FROM " . self::TABLE . " WHERE application = ? AND `key` = ? AND expiration >= NOW()", $application, $key)->fetch();
     if ($row) {
         $entity = new Apikey();
         $entity->setId($row['id']);
         $entity->setApplication($row['application']);
         $entity->setKey($row['key']);
         $entity->setExpiration($row['expiration']);
         return $entity;
     }
     return FALSE;
 }
コード例 #7
0
ファイル: BasePresenter.php プロジェクト: amertak/Fractions
 private function ensureUser()
 {
     if (!$this->getUser()->isLoggedIn()) {
         $this->database->query("INSERT INTO `users`", array("id" => null));
         $us = $this->database->table('users')->where('id = ?', $this->database->getInsertId())->fetch();
         $this->user->setExpiration('365 days', FALSE);
         $this->user->login(new \Nette\Security\Identity($us->id, null, $us));
     } else {
         $us = $this->database->table('users')->where('id = ?', $this->user->getId())->fetch();
         if ($us == null) {
             $this->user->logout(true);
         }
     }
 }
コード例 #8
0
ファイル: bootstrap.php プロジェクト: pogodi/Brain
function purge(\Nette\Database\Context $context)
{
    /* For mysql */
    $tables = $context->query("SELECT TABLE_NAME AS t FROM `INFORMATION_SCHEMA`.`TABLES` WHERE TABLE_SCHEMA = 'test' ")->fetchAll();
    if ($tables) {
        $arr = [];
        foreach ($tables as $table) {
            $arr[] = $table['t'];
        }
        $context->query("SET foreign_key_checks = 0");
        $context->query("DROP TABLE " . implode(", ", $arr));
        $context->query("SET foreign_key_checks = 1");
    }
}
コード例 #9
0
ファイル: DbTool.php プロジェクト: filsedla/dbtool
 private function processViews()
 {
     $tables = $this->db->getConnection()->getSupplementalDriver()->getTables();
     foreach ($tables as $table) {
         if ($table['view'] == TRUE) {
             $viewName = $table['name'];
             // Fetch SHOW CREATE VIEW string
             $row = $this->db->query("SHOW CREATE VIEW `{$viewName}`")->fetch();
             $createView = $row["Create View"];
             // Remove Auto increment value
             $createView = Strings::replace($createView, '#SQL SECURITY DEFINER\\s?#i');
             $createView = Strings::replace($createView, '#ALGORITHM=UNDEFINED\\s?#i');
             $createView = Strings::replace($createView, '/DEFINER=`.+?`\\@`.+?`\\s?/');
             // Add ;
             $createView .= ";";
             $dropTable = "DROP VIEW IF EXISTS `{$viewName}`;\n";
             $data = Data::header() . $dropTable . $createView . "\n" . Data::footer();
             $dump = new Dump($viewName, Dump::TYPE_VIEW, $this->dumpDir);
             $dump->saveIfChanged($data, function ($fromFile) use($createView) {
                 $createViewFromFile = Strings::match($fromFile, "/CREATE.*;/s")[0];
                 return Strings::normalize($createViewFromFile) == Strings::normalize($createView);
             });
         }
     }
 }
コード例 #10
0
 public function add(IEntity $parent, array $add)
 {
     $this->mapperOne->beginTransaction();
     $list = $this->buildList($parent, $add);
     $builder = new SqlBuilder($this->joinTable, $this->context);
     $this->context->query($builder->buildInsertQuery(), $list);
 }
コード例 #11
0
 /**
  * Ze zvoleneho txt souboru vybere vysledky domacich plavcu
  * @param string $file_name Vstupni txt soubor
  * @param string $event_id Identifikator zavodu
  * @param string $delimiter Oddelovac poli
  * @param int $length Maximalni delka radku
  * @return array Informace o poctu chyb a nactenych zaznamu
  */
 public function getImportData($file_name, $id_event, $delimiter = ";", $length = 1000)
 {
     setlocale(LC_CTYPE, 'cs_CZ.UTF-8');
     // V pripade chyby fopen vrati FALSE
     if (!($this->fp = @fopen($file_name, "r"))) {
         $this->status["fileok"] = FALSE;
         return $this->status;
     }
     $this->id_event = $id_event;
     $this->delimiter = $delimiter;
     $this->length = $length;
     // Prochazi se vsechny radky vstupniho souboru
     while (($row = fgetcsv($this->fp, $this->length, $this->delimiter)) !== FALSE) {
         // Z radku se nactou pouze pozadovane polozky
         $this->selectRow($row);
     }
     // Ulozi se pocet nactenych zaznamu
     $this->status["recnum"] = count($this->data);
     // Vymaz pomocne tabulky
     $this->database->query('TRUNCATE TABLE sm_import');
     // Naplneni pomocne tabulky
     $this->database->query('INSERT INTO sm_import', $this->data);
     // Vraceni informace o poctu chyb a nactenych zaznamu
     return $this->status;
 }
コード例 #12
0
ファイル: Changelog.php プロジェクト: lovec/db-changelog
 /**
  * @param Selection|ActiveRow[]
  * @return array
  */
 public function executeQueries(Selection $queries)
 {
     $errors = [];
     foreach ($queries as $query) {
         try {
             $this->database->query($query->query);
             // update query as executed
             $query->update(['executed' => 1]);
         } catch (\Exception $e) {
             // save information about error in query
             $query->update(['error' => $e->getMessage()]);
             $errors[$query->getPrimary()] = $e->getMessage();
         }
     }
     return $errors;
 }
コード例 #13
0
ファイル: DbChangelog.php プロジェクト: RiKap/ErrorMonitoring
 public function executeQueries(\Nette\Database\Table\Selection $queries)
 {
     $errors = array();
     foreach ($queries as $query) {
         try {
             $test = $this->connection->query($query->query);
             // update query as executed
             $query->update(array('executed' => 1));
         } catch (\Exception $e) {
             // save information about error in query
             $query->update(array('error' => $e->getMessage()));
             $errors[$query->id] = $e->getMessage();
         }
     }
     return $errors;
 }
コード例 #14
0
 public function invoke(Container $container, Context $db)
 {
     $driver = new PostgreSqlNetteDbDriver($db, 'migrations');
     $printer = new Console();
     $runner = new Runner($driver, $printer);
     if ($this->in->getOption('init')) {
         ob_start();
         $runner->run($runner::MODE_INIT);
         $sql = ob_get_clean();
         $db->query($sql);
         $this->out->writeln('<info>Migrations table created</info>');
         return;
     }
     $g = new Group();
     $g->directory = __DIR__ . '/../../../migrations/struct';
     $g->dependencies = [];
     $g->enabled = TRUE;
     $g->name = 'struct';
     $runner->addGroup($g);
     $runner->addExtensionHandler('sql', new Extensions\NetteDbSql($db));
     $runner->addExtensionHandler('php', new PhpClass(['db' => $db], $container));
     try {
         $runner->run();
         return;
     } catch (\PDOException $e) {
         if ($e->getCode() !== '42S02') {
             throw $e;
         }
         // lets hope locale is english
         if (!preg_match("~Table '.*?\\.migrations' doesn't exist~", $e->getMessage())) {
             throw $e;
         }
         $this->out->writeln('<error>Migrations table does not exist, init migrations first</error>');
     }
 }
コード例 #15
0
ファイル: Category.php プロジェクト: caloriscz/caloriscms
 /**
  * Create new category
  */
 function setCategory($title, $parent, $slug = null)
 {
     if (is_numeric($parent) == false) {
         $parent = null;
     }
     $this->database->table("categories")->insert(array("title" => $title, "parent_id" => $parent));
     $this->database->query("UPDATE categories SET sorted = id WHERE sorted = 0");
 }
コード例 #16
0
ファイル: Request.php プロジェクト: trejjam/authorization
 protected function getSqlTime()
 {
     if (isset($this->sqlTime)) {
         return $this->sqlTime;
     }
     $q = $this->database->query('SELECT NOW() as now;');
     return $this->sqlTime = $q->fetch()->now;
 }
コード例 #17
0
 public function insertFormSucceeded(\Nette\Forms\BootstrapUIForm $form)
 {
     if (is_numeric($form->values->parent) == false) {
         $arr["parent_id"] = null;
     } else {
         $arr["parent_id"] = $form->values->parent;
     }
     $arr['title'] = $form->values->title;
     $arr['url'] = $form->values->url;
     $languages = $this->database->table("languages")->where(array("default" => null, "used" => 1));
     foreach ($languages as $item) {
         $arr["url_" . $item->code] = $form->values->{'url_' . $item->code};
         $arr["title_" . $item->code] = $form->values->{'title_' . $item->code};
     }
     $this->database->table("menu")->insert($arr);
     $this->database->query("SET @i = 1;UPDATE `menu` SET `sorted` = @i:=@i+2 ORDER BY `sorted` ASC");
     $this->presenter->redirect(this, array("id" => null));
 }
コード例 #18
0
ファイル: UpdatorService.php プロジェクト: meridius/yadup
 /**
  * Import taken from Adminer, slightly modified
  *
  * @param string $query
  * @return int number of done queries OR array in case of error
  *
  * @author Jakub Vrána, Jan Tvrdík, Michael Moravec, Martin Lukeš
  * @license Apache License
  */
 private function parseAndRunFile($query)
 {
     $delimiter = ';';
     $offset = 0;
     $state = array();
     try {
         $this->db->beginTransaction();
         while ($query != '') {
             if (!$offset && preg_match('~^\\s*DELIMITER\\s+(.+)~i', $query, $match)) {
                 $delimiter = $match[1];
                 $query = substr($query, strlen($match[0]));
             } else {
                 preg_match('(' . preg_quote($delimiter) . '|[\'`"]|/\\*|-- |#|$)', $query, $match, PREG_OFFSET_CAPTURE, $offset);
                 // should always match
                 $found = $match[0][0];
                 $offset = $match[0][1] + strlen($found);
                 if (!$found && rtrim($query) === '') {
                     break;
                 }
                 if (!$found || $found == $delimiter) {
                     // end of a query
                     $q = substr($query, 0, $match[0][1]);
                     //change definer (must be previously definened)
                     if (!empty($this->definerUser) || !empty($this->definerHost)) {
                         $definerMatches = array();
                         preg_match('/(DEFINER\\s*=\\s*)(`[^`]+`)@(`[^`]+`)/', $q, $definerMatches);
                         $newUser = empty($this->definerUser) ? $definerMatches[2] : $this->definerUser;
                         $newHost = empty($this->definerHost) ? $definerMatches[3] : $this->definerHost;
                         $q = preg_replace('/(DEFINER\\s*=\\s*)(`[^`]+`)@(`[^`]+`)/', '$1`' . $newUser . '`@`' . $newHost . '`', $q);
                     }
                     $state[] = $this->db->query($q);
                     $query = substr($query, $offset);
                     $offset = 0;
                 } else {
                     // find matching quote or comment end
                     while (preg_match('~' . ($found == '/*' ? '\\*/' : (preg_match('~-- |#~', $found) ? "\n" : "{$found}|\\\\.")) . '|$~s', $query, $match, PREG_OFFSET_CAPTURE, $offset)) {
                         //! respect sql_mode NO_BACKSLASH_ESCAPES
                         $s = $match[0][0];
                         $offset = $match[0][1] + strlen($s);
                         if ($s[0] !== '\\') {
                             break;
                         }
                     }
                 }
             }
         }
         $this->db->commit();
         $result = count($state);
     } catch (\Exception $ex) {
         $this->db->rollBack();
         $result = array("message" => $ex->getMessage(), "sql" => $q);
     }
     $this->db->query('USE `' . $this->dbName . '`');
     // revert used database
     return $result;
 }
コード例 #19
0
ファイル: NetteMapper.php プロジェクト: Zarganwar/orm
 public function remove(IEntity $entity)
 {
     $this->beginTransaction();
     $id = (array) $entity->getPersistedId();
     $primary = [];
     foreach ($this->getStorageReflection()->getStoragePrimaryKey() as $key) {
         $primary[$key] = array_shift($id);
     }
     $this->databaseContext->query('DELETE FROM ' . $this->getTableName() . ' WHERE ?', $primary);
 }
コード例 #20
0
 private function upload_photos($id_inzerat)
 {
     // upload new photos
     foreach ($this->inzerat['photo'] as $image) {
         // image into DB
         $file_name = pathinfo($image->name, PATHINFO_FILENAME);
         $ext = pathinfo($image->name, PATHINFO_EXTENSION);
         $this->database->query('INSERT INTO image (id_poster, name, extension) VALUES (' . $id_inzerat . ',"' . $file_name . '","' . $ext . '")');
         // image onto server
         $id_image = $this->database->getInsertId();
         $target_dir = 'images/';
         $target_file = $target_dir . $id_image . '.' . $ext;
         if (move_uploaded_file($image->getTemporaryFile(), $target_file)) {
             // success
         } else {
             // error
         }
     }
 }
コード例 #21
0
ファイル: Trees.php プロジェクト: trejjam/authorization
 protected function createResourceTree(Nette\Database\Context $database, array $tables)
 {
     if (!$database->query("SHOW TABLES LIKE '" . $tables["resource"]["table"] . "'")->getRowCount()) {
         throw new Trejjam\Authorization\TableNotFoundException("Table " . $tables["resource"]["table"] . " not exist", Trejjam\Authorization\TableNotFoundException::TABLE_NOT_FOUND);
     }
     foreach ($database->table($tables["resource"]["table"]) as $v) {
         $tableInfo = $tables["resource"];
         unset($tableInfo["table"]);
         $this->registerResource(new Resource($v, $tableInfo));
     }
 }
コード例 #22
0
 /**
  * Import taken from Adminer, slightly modified
  *
  * @param    string path to imported file
  * @param    DibiConnection
  * @returns  int number of executed queries
  *
  * @author   Jakub Vrána
  * @author   Jan Tvrdík
  * @author   Michael Moravec
  * @author   Jan Skrasek
  * @license  Apache License
  */
 protected function loadFile($file)
 {
     $query = @file_get_contents($file);
     if (!$query) {
         throw new IOException("Cannot open file '{$file}'.");
     }
     $delimiter = ';';
     $offset = $queries = 0;
     $space = "(?:\\s|/\\*.*\\*/|(?:#|-- )[^\\n]*\\n|--\\n)";
     $driver = $this->context->getConnection()->getSupplementalDriver();
     if ($driver instanceof MsSqlDriver) {
         $parse = '[\'"[]|/\\*|-- |$';
     } elseif ($driver instanceof SqliteDriver) {
         $parse = '[\'"`[]|/\\*|-- |$';
     } elseif ($driver instanceof PgSqlDriver) {
         $parse = '[\'"]|/\\*|-- |$|\\$[^$]*\\$';
     } else {
         $parse = '[\'"`#]|/\\*|-- |$';
     }
     while ($query != '') {
         if (!$offset && preg_match("~^{$space}*DELIMITER\\s+(\\S+)~i", $query, $match)) {
             $delimiter = $match[1];
             $query = substr($query, strlen($match[0]));
         } else {
             preg_match('(' . preg_quote($delimiter) . "\\s*|{$parse})", $query, $match, PREG_OFFSET_CAPTURE, $offset);
             // should always match
             $found = $match[0][0];
             $offset = $match[0][1] + strlen($found);
             if (!$found && rtrim($query) === '') {
                 break;
             }
             if (!$found || rtrim($found) == $delimiter) {
                 // end of a query
                 $q = substr($query, 0, $match[0][1]);
                 $queries++;
                 $this->context->query($q);
                 $query = substr($query, $offset);
                 $offset = 0;
             } else {
                 // find matching quote or comment end
                 while (preg_match('(' . ($found == '/*' ? '\\*/' : ($found == '[' ? ']' : (preg_match('~^-- |^#~', $found) ? "\n" : preg_quote($found) . "|\\\\."))) . '|$)s', $query, $match, PREG_OFFSET_CAPTURE, $offset)) {
                     //! respect sql_mode NO_BACKSLASH_ESCAPES
                     $s = $match[0][0];
                     $offset = $match[0][1] + strlen($s);
                     if ($s[0] !== '\\') {
                         break;
                     }
                 }
             }
         }
     }
     return $queries;
 }
コード例 #23
0
ファイル: ImportTimePresenter.php プロジェクト: jave007/iSAM
 /**
  * Zpracuje formulář pro import vysledku 
  * @param type $form 
  * @param type $values
  */
 public function importTimeFormSucceeded($form, $values)
 {
     // Vizualni kontrola chyb po nacteni vysledku do pomocne tabulky
     $this->template->status = $this->importTimeManager->getImportData($values->file, $values->event_id);
     if ($this->database->table('sm_import')->count() === 0) {
         $this->template->sm_import_status = FALSE;
     } else {
         $this->template->sm_import_status = TRUE;
     }
     if ($form['check']->isSubmittedBy()) {
         if ($this->template->status['fileok'] === FALSE) {
             $this->flashMessage('Zvolený soubor nelze otevřít.', 'error');
         } elseif ($this->template->status['recnum'] === 0) {
             $this->flashMessage('Načtený soubor neobsahuje výsledky oddílu ASK Blansko.', 'error');
         } elseif ($this->database->query('SELECT id FROM sm_time WHERE id_event = ?', $values->event_id)->getRowCount() > 0) {
             $this->flashMessage('Zvolený závod už obsahuje záznamy v tabulce časů.', 'error');
             $this->template->status['fileok'] = FALSE;
         } else {
             $this->template->data = $this->database->table('sm_import');
         }
     } elseif ($form['import']->isSubmittedBy()) {
         if ($this->template->sm_import_status === FALSE) {
             $this->flashMessage('Nejprve nahrajte soubor s výsledky a zkontrolujte jejich správnost.', 'error');
         } else {
             $this->database->query('INSERT INTO sm_time
                                     (
                                         id_event,
                                         id_stroke,
                                         id_swimmer,
                                         time,
                                         rank,
                                         point
                                     ) 
                                     SELECT * FROM sm_import');
             $this->database->query('DELETE FROM sm_import');
             $this->flashMessage('Data byla importována.', 'success');
         }
     }
 }
コード例 #24
0
ファイル: HomepagePresenter.php プロジェクト: spaze/cotel
 public function submittedMedia(\Cotel\Form\MediaForm $form)
 {
     $values = $form->getValues();
     $tags = array_filter(preg_split('/\\s+/', $values->tags));
     $this->database->beginTransaction();
     $this->database->query('INSERT INTO urls', array('url' => $values->url, 'title' => $values->title, 'published' => new \DateTime($values->published), 'added' => new \DateTime('now')));
     $urlId = $this->database->getInsertId();
     $tagIds = array();
     foreach ($tags as $tag) {
         $this->database->query('INSERT INTO tags ? ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id)', array('tag' => $tag));
         $this->database->query('INSERT INTO url_tags', ['url_id' => $urlId, 'tag_id' => $this->database->getInsertId()]);
     }
     $this->database->commit();
     $this->redirect('this');
 }
コード例 #25
0
ファイル: Database.php プロジェクト: filsedla/hyperrow
 /**
  * @return void
  */
 public function rollBack()
 {
     if ($this->config->isNestedTransactions()) {
         $this->transactionLevel--;
         if ($this->transactionLevel == 0) {
             $this->context->rollBack();
         } elseif ($this->transactionLevel > 0) {
             $this->context->query("ROLLBACK TO SAVEPOINT level{$this->transactionLevel}");
         } else {
             throw new InvalidStateException("Negative transaction level. Check if each commit/rollBack has its corresponding beginTransaction.");
         }
     } else {
         $this->context->rollBack();
     }
 }
コード例 #26
0
 /**
  * Podle zadaneho roku prepocte body u vsech casu v tabulce sm_time
  * @param string $year Rok z tabulky sm_bt
  * @return array Informace o vysledku prepoctu
  */
 public function runRecalculatePoints($year)
 {
     set_time_limit(0);
     // Vypnuti vlastnosti brzdici update
     $this->database->query('SET autocommit=0');
     $this->database->query('SET unique_checks=0');
     $this->database->query('SET foreign_key_checks=0');
     $this->database->query('START TRANSACTION');
     // Postupne prochazeni vsech radku tabulky
     $tabulka = $this->database->table($this->tableName);
     foreach ($tabulka as $radek) {
         $this->prepocetBodu($year, $radek->id, $radek->id_event, $radek->id_stroke, $radek->id_swimmer, $radek->time);
     }
     // Zapnuti
     $this->database->query('COMMIT');
     $this->database->query('SET foreign_key_checks=1');
     $this->database->query('SET unique_checks=1');
     $this->database->query('SET autocommit=1');
     // Vraceni informace o txt souboru, poctu chyb a nactenych zaznamu
     return $this->status;
 }
コード例 #27
0
ファイル: Selection.php プロジェクト: jave007/test
 /**
  * Inserts row in a table.
  * @param  array|\Traversable|Selection array($column => $value)|\Traversable|Selection for INSERT ... SELECT
  * @return IRow|int|bool Returns IRow or number of affected rows for Selection or table without primary key
  */
 public function insert($data)
 {
     if ($data instanceof self) {
         $return = $this->context->queryArgs($this->sqlBuilder->buildInsertQuery() . ' ' . $data->getSql(), $data->getSqlBuilder()->getParameters());
     } else {
         if ($data instanceof \Traversable) {
             $data = iterator_to_array($data);
         }
         $return = $this->context->query($this->sqlBuilder->buildInsertQuery() . ' ?values', $data);
     }
     $this->loadRefCache();
     if ($data instanceof self || $this->primary === NULL) {
         unset($this->refCache['referencing'][$this->getGeneralCacheKey()][$this->getSpecificCacheKey()]);
         return $return->getRowCount();
     }
     $primarySequenceName = $this->getPrimarySequence();
     $primaryKey = $this->context->getInsertId(!empty($primarySequenceName) ? $this->context->getConnection()->getSupplementalDriver()->delimite($primarySequenceName) : $primarySequenceName);
     if ($primaryKey === FALSE) {
         unset($this->refCache['referencing'][$this->getGeneralCacheKey()][$this->getSpecificCacheKey()]);
         return $return->getRowCount();
     }
     if (is_array($this->getPrimary())) {
         $primaryKey = array();
         foreach ((array) $this->getPrimary() as $key) {
             if (!isset($data[$key])) {
                 return $data;
             }
             $primaryKey[$key] = $data[$key];
         }
         if (count($primaryKey) === 1) {
             $primaryKey = reset($primaryKey);
         }
     }
     $row = $this->createSelectionInstance()->select('*')->wherePrimary($primaryKey)->fetch();
     if ($this->rows !== NULL) {
         if ($signature = $row->getSignature(FALSE)) {
             $this->rows[$signature] = $row;
             $this->data[$signature] = $row;
         } else {
             $this->rows[] = $row;
             $this->data[] = $row;
         }
     }
     return $row;
 }
コード例 #28
0
 public function gc($maxLifeTime)
 {
     $maxTimestamp = time() - $maxLifeTime;
     // Try to avoid a conflict when running garbage collection simultaneously on two
     // MySQL servers at a very busy site in a master-master replication setup by
     // subtracting one tenth of $maxLifeTime (but at least one day) from $maxTimestamp
     // for each server with reasonably small ID except for the server with ID 1.
     //
     // In a typical master-master replication setup, the server IDs are 1 and 2.
     // There is no subtraction on server 1 and one day (or one tenth of $maxLifeTime)
     // subtraction on server 2.
     $serverId = $this->context->query("SELECT @@server_id as `server_id`")->fetch()->server_id;
     if ($serverId > 1 && $serverId < 10) {
         $maxTimestamp -= ($serverId - 1) * max(86400, $maxLifeTime / 10);
     }
     $this->context->table($this->tableName)->where('timestamp < ?', $maxTimestamp)->delete();
     return TRUE;
 }
コード例 #29
0
 public function handleRezervaceForm()
 {
     $input = file_get_contents('php://input');
     $data = json_decode($input);
     if (isset($data->rezervace_id)) {
         $od = new \DateTime($data->datumod);
         $do = new \DateTime($data->datumdo);
         $data->datum_od = $od->format('Y-m-d');
         $data->datum_do = $do->format('Y-m-d');
         unset($data->datumdo);
         unset($data->datumod);
         $this->database->table('rezervace')->get($data->rezervace_id)->update((array) $data);
         $this->payload->rezervace = $data;
         $this->database->table('rezervace')->get($data->rezervace_id)->related('rezervace_day')->delete();
         while ($od <= $do) {
             $this->database->table('rezervace_day')->insert(array('datum' => $od->format('Y-m-d'), 'rezervace_id' => $data->rezervace_id));
             $od->modify('+1 day');
         }
         $this->payload->status = true;
         $this->payload->id = $data->rezervace_id;
         $height = $this->database->query("SELECT position FROM rezervace WHERE apartman_id=? ORDER BY position desc limit 1", $data->apartman_id)->fetch();
         $this->database->query("UPDATE apartman SET height = ? WHERE apartman_id=?", $height['position'], $data->apartman_id);
     } else {
         $od = new \DateTime($data->datumod);
         $do = new \DateTime($data->datumdo);
         $data->datum_od = $od->format('Y-m-d');
         $data->datum_do = $do->format('Y-m-d');
         unset($data->datumdo);
         unset($data->datumod);
         $rezervace = $this->database->table('rezervace')->insert((array) $data);
         $this->payload->rezervace = $data;
         while ($od <= $do) {
             $this->database->table('rezervace_day')->insert(array('datum' => $od->format('Y-m-d'), 'rezervace_id' => $rezervace->rezervace_id));
             $od->modify('+1 day');
         }
         $this->payload->status = true;
         $this->payload->id = $rezervace->rezervace_id;
         $this->payload->apartmany = $this->database->table('apartman');
         $height = $this->database->query("SELECT position FROM rezervace WHERE apartman_id=? ORDER BY position desc limit 1", $data->apartman_id)->fetch();
         $this->database->query("UPDATE apartman SET height = ? WHERE apartman_id=?", $height['position'], $data->apartman_id);
     }
     $this->sendPayload();
 }
コード例 #30
0
ファイル: Rss.php プロジェクト: stanley89/piratskelisty
 public function loadLob()
 {
     $stop = $this->database->fetchField("select max(unix_timestamp(published))>(unix_timestamp(now())-100) from lob_items;");
     if ($stop) {
         return;
     }
     $channels = $this->getLobChannels();
     foreach ($channels as $channel) {
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $channel['link']);
         $redirects = 0;
         $page = $this->curl_redirect_exec($ch, $redirects, true);
         curl_close($ch);
         if (empty($page)) {
             continue;
         }
         $html = HtmlDomParser::str_get_html($page);
         foreach ($html->find('#page-body .post') as $element) {
             if (isset($element->id)) {
                 $id = preg_replace("/[^0-9,.]/", "", $element->id);
             } else {
                 continue;
             }
             $lobItem = $this->getLobItemByPostId($id);
             if (!empty($lobItem)) {
                 continue;
             }
             $arr = array();
             $content = $element->find('.content', 0);
             $author = $element->find('.postprofile dt', 0);
             $datestring = $element->find('.author', 0);
             $arr['content'] = trim($content->innertext);
             $arr['author'] = trim($author->plaintext);
             $arr['datestring'] = trim(preg_replace("/.*&raquo;/", "", $datestring->innertext));
             $arr['post_id'] = $id;
             $this->database->query('insert into lob_items ', $arr);
         }
     }
 }