public function read($params, AccountWriter $writer)
 {
     $args = new FormattedArgumentMap($params);
     $folder = $args->opt("i", "plugins/SimpleAuth");
     if (!is_dir($folder)) {
         throw new \InvalidArgumentException("Input database {$folder} not found or is not a directory");
     }
     $path = rtrim($folder, "/\\") . "/players.db";
     if (!is_file($path)) {
         return;
     }
     $this->setStatus("Opening database");
     $db = new \SQLite3($path);
     $result = $db->query("SELECT COUNT(*) AS cnt FROM players");
     $total = $result->fetchArray(SQLITE3_ASSOC)["cnt"];
     $result->finalize();
     $this->setStatus("Preparing data");
     $result = $db->query("SELECT name,registerdate,logindate,lastip,hash FROM players");
     $i = 0;
     while (is_array($row = $result->fetchArray(SQLITE3_ASSOC))) {
         $i++;
         $info = AccountInfo::defaultInstance($row["name"], $this->defaultOpts);
         $info->lastIp = $row["lastip"];
         $info->registerTime = $row["registerdate"];
         $info->lastLogin = $row["logindate"];
         $info->passwordHash = hex2bin($row["hash"]);
         $writer->write($info);
         $this->setProgress($i / $total);
     }
     $db->close();
 }
function getEvents()
{
    global $db;
    $token = trim(file_get_contents('config/token.txt'));
    $mainPage = pullUrl("https://techspring.nationbuilder.com/api/v1/sites/v2/pages/events?starting=" . date("Y-m-d") . "&access_token=" . $token . "");
    $obj = json_decode($mainPage);
    //echo "<pre>" . json_encode($obj, JSON_PRETTY_PRINT) . "</pre>";
    if ($db = new SQLite3('local_db.sql')) {
        $q = @$db->query('CREATE TABLE IF NOT EXISTS events (eid INTEGER, start_time TEXT, end_time TEXT, name TEXT, description TEXT, PRIMARY KEY(eid))');
        $q = @$db->query('CREATE TABLE IF NOT EXISTS rsvp (eid INTEGER, uid INTEGER)');
    }
    foreach ($obj->results as $eventObj) {
        echo "<br/>{$eventObj->id} - {$eventObj->name} - {$eventObj->start_time} - {$eventObj->end_time} - {$eventObj->intro} <br />";
        $startTime = strtotime($eventObj->start_time);
        $endTime = strtotime($eventObj->end_time);
        echo "Date: " . date("l, F jS", $startTime);
        echo "<br />Time:" . date("g:i a", $startTime) . " - " . date("g:i a", $endTime) . "<br />";
        @$db->query("INSERT OR IGNORE INTO `events` (eid, start_time, end_time, name, description) VALUES " . "('" . $eventObj->id . "'," . "'" . $eventObj->start_time . "'," . "'" . $eventObj->end_time . "'," . "'" . $eventObj->name . "'," . "'" . $eventObj->intro . "');");
    }
    $eventRes = @$db->query("SELECT * FROM `events`");
    while ($event = $eventRes->fetchArray()) {
        $json = pullUrl("https://techspring.nationbuilder.com/api/v1/sites/v2/pages/events/" . $event['eid'] . "/rsvps?limit=10&__proto__=&access_token=" . $token);
        $rsvpData = json_decode($json);
        foreach ($rsvpData->results as $rsvp) {
            @$db->query("INSERT OR IGNORE INTO `rsvp` (eid, uid) VALUES ('" . $event['eid'] . "','" . $rsvp->person_id . "')");
        }
    }
}
 public function tearDown()
 {
     $sql = 'DELETE FROM merchants';
     self::$dbConnection->query($sql);
     $sql = 'DELETE FROM transactions';
     self::$dbConnection->query($sql);
 }
    /**
     * Create Tables needed for storing information about apps.
     *
     * @throws DBAppsException
     *  If a create table query fails.
     */
    protected function createTables()
    {
        $sqls = array(<<<'EOF'
-- Table for listing top free apps from google.
CREATE TABLE IF NOT EXISTS topApps
(
    package TEXT, -- The package name of the app.
    rank INT, -- The rank of the app in the top apps list.
    PRIMARY KEY(package)
);
EOF
, <<<'EOF'
-- Table for listing all apps from google.
CREATE TABLE IF NOT EXISTS Apps
(
    package TEXT, -- The package name of the app.
    title TEXT, -- The title of the app (human readable).
    author TEXT, -- The author of the app.
    description TEXT, -- The description text of the app.
    PRIMARY KEY(package)
);
EOF
);
        foreach ($sqls as $sql) {
            if ($this->db->query($sql) === FALSE) {
                throw new DBAppsException(_('Failed to create tables.'));
            }
        }
    }
Exemple #5
0
 /**
  * Query
  * 
  * @param mixed $query
  */
 function sql_query($query)
 {
     if (empty($query)) {
         core::dprint('Empty sql_query call');
         return false;
     }
     if (is_array($query)) {
         $query = vsprintf($query[0], array_slice($query, 1));
     }
     $query = trim($query);
     if (empty($query)) {
         return false;
     }
     if (!$this->_connect()) {
         return false;
     }
     ++$this->_counter;
     $this->_sqlite_fixes($query);
     $this->_last_query = $query;
     $is_select = preg_match('@^(SELECT|PRAGMA)@i', $query);
     $microtime = microtime(1);
     // how the f**k to catch errors in query?
     $this->query_result = $is_select ? @$this->_connect_id->query($query) : @$this->_connect_id->exec($query);
     $this->_last_query_time = microtime(1) - $microtime;
     core::dprint(array('[SQL%0d|%.5f : %s', $this->_counter, $this->_last_query_time, $query), core::E_SQL);
     if (!$this->query_result) {
         $err = $this->sql_error();
         core::dprint('[SQL FAIL] ' . $err['message'] . ' : ' . $err['code'], core::E_SQL);
     }
     return $this->query_result;
 }
 /**
  * The primary method a driver needs to implement is the execute method, which takes an array of query options.
  * The options in the array varies, but the key type will always be supplied, which will be either SELECT, UPDATE,
  * INSERT, REPLACE or DELETE.
  *
  * @param array $options An array of options that were generated through use of the Query class.
  * @return object It is expected to return an instance of an \Queryer\Driver\DatabaseDriverResult class.
  * @see \Queryer\Query, \Queryer\Driver\DatabaseDriverResult
  */
 public function execute(array $options)
 {
     $query = self::generateQuery($options);
     $query = DatabaseTools::replaceVariables($query, $options['variables']);
     $result = $this->sqlite->query($query);
     return new Sqlite3DriverResult($result, $this->sqlite->changes(), $this->sqlite->lastInsertRowID(), $result === false ? $this->sqlite->lastErrorCode() : null, $result === false ? $this->sqlite->lastErrorMsg() : null, $query);
 }
Exemple #7
0
function get_mbtiles_data($file_path)
{
    $db_mbtiles = new SQLite3($file_path);
    // Min Zoom and Max Zoom
    $zoom_range_query = "select min(zoom_level), max(zoom_level) from tiles";
    $zoom_range_results = $db_mbtiles->query($zoom_range_query);
    $zoom_range = $zoom_range_results->fetchArray();
    $min_zoom = $zoom_range[0];
    $max_zoom = $zoom_range[1];
    // Get zoom, column, and row for each tile
    $query = "select zoom_level, avg(tile_column), avg(tile_row) from tiles group by zoom_level";
    $results = $db_mbtiles->query($query);
    $rows = array();
    while ($row = $results->fetchArray()) {
        $rows[] = $row;
    }
    $center_tile = $rows[floor(0.5 * count($rows))];
    $center_tile_zoom = $center_tile[0];
    $center_tile_x = floor($center_tile[1]);
    // Column
    $center_tile_y = round(pow(2, $center_tile_zoom) - $center_tile[2] - 1);
    // Converted Row
    $mbtiles_data = array("min_zoom" => $min_zoom, "max_zoom" => $max_zoom, "center_coordinates" => array("zoom" => $center_tile_zoom, "x" => intval($center_tile_x), "y" => intval($center_tile_y)));
    return $mbtiles_data;
}
function save_pois($jsonStr, $dbname)
{
    //create or open the channel database
    $db = new SQLite3($dbname, SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE);
    //create the POIs table
    $db->query("CREATE TABLE IF NOT EXISTS POIsM (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, description TEXT, phoneNumber TEXT, homepage TEXT, iconURL TEXT, thumbnailURL TEXT, imageURL TEXT,\n                videoURL TEXT, soundURL TEXT, modelURL TEXT, latitude REAL, longitude REAL, altitude REAL) ;");
    $db->query("DELETE FROM POIsM;");
    //required because we bulk-replace all POIs on updates to the channel
    $db->query("UPDATE SQLITE_SEQUENCE SET seq='0' WHERE name='POIsM';");
    //reset the id count to start from 1 again; Else, the id count starts from the previously used highest id for the table
    //Decode the json string to UTF-8 encoding as "json_decode" only works for UTF-8 encoding
    $poisJson = json_decode(utf8_decode($jsonStr));
    $objects = $poisJson->pois;
    //parse the input json for POI information
    foreach ($objects as $obj) {
        $description = "";
        $phoneNumber = "";
        $icon = "";
        $thumbnail = "";
        print_r($obj);
        $homepage = "";
        $imageUrl = "";
        $movieUrl = "";
        $soundUrl = "";
        //Check if attributes needed for POI are present in JSON
        if (isset($obj->description)) {
            $description = $obj->description;
        }
        if (isset($obj->phoneNumber)) {
            $phoneNumber = $obj->phoneNumber;
        }
        if (isset($obj->iconURL)) {
            $icon = $obj->iconURL;
        } else {
            $icon = "http://channels.excel.junaio.com/resources/icon_thumbnail.png";
        }
        if (isset($obj->thumbnailURL)) {
            $thumbnail = $obj->thumbnailURL;
        } else {
            $thumbnail = "http://channels.excel.junaio.com/resources/icon_thumbnail.png";
        }
        if (isset($obj->homepage)) {
            $homepage = $obj->homepage;
        }
        if (isset($obj->imageURL)) {
            $imageUrl = $obj->imageURL;
        }
        if (isset($obj->video)) {
            $movieUrl = $obj->video;
        }
        if (isset($obj->sound)) {
            $soundUrl = $obj->sound;
        }
        //insert each POI to the db
        $query = "INSERT INTO POIsM (title, description, phoneNumber, homepage, iconURL, thumbnailURL, imageURL, videoURL,\n        soundURL, modelURL, latitude, longitude, altitude) VALUES ('" . $obj->title . "', '" . $description . "',\n        '" . $phoneNumber . "', '" . $homepage . "', '" . $icon . "', '" . $thumbnail . "', '" . $imageUrl . "', '" . $movieUrl . "', '" . $soundUrl . "', '', '" . $obj->latitude . "', '" . $obj->longitude . "', '" . $obj->altitude . "');";
        $db->query($query);
    }
    $db->close();
}
 /**
  * 
  * @param string $query
  * @return array
  */
 public function sendSelectQuery($query)
 {
     $result = $this->db->query($query);
     while ($fetch = $result->fetchArray(SQLITE3_ASSOC)) {
         $resultList[] = $fetch;
     }
     return is_array($resultList) ? $resultList : [];
 }
 protected function fetchPlayer($name)
 {
     $result = $this->db->query("SELECT * FROM selected_tools WHERE player = {$this->escape($name)};");
     $data = [];
     while (is_array($dat = $result->fetchArray(SQLITE3_ASSOC))) {
         $data[] = $dat;
     }
     return $data;
 }
 /**
  * Query and get results
  *
  * @param string $sql
  * @param bool   $parse Parse or return as is
  * @param bool   $debug
  * @return array
  */
 public function query($sql, $parse = true, $debug = false)
 {
     $result = array();
     $statement = $this->db->query($sql);
     while ($row =& $statement->fetchArray(SQLITE3_ASSOC)) {
         $result[] = $row;
     }
     return $result;
 }
Exemple #12
0
 public function getArray($sSql)
 {
     $aReturn = [];
     $oQuery = @$this->__db->query($sSql);
     if ($oQuery !== false) {
         while ($aRow = $oQuery->fetchArray(SQLITE3_ASSOC)) {
             array_push($aReturn, $aRow);
         }
     }
     return $aReturn;
 }
Exemple #13
0
 /**
  * Function fetches all rows out of the DB and returns an array of Model/Company objects
  * @return \Model\Company[]
  */
 public function getAll()
 {
     $retArr = array();
     $sql = 'SELECT * FROM companyDetails';
     $rs = $this->db->query($sql);
     while ($row = $rs->fetchArray()) {
         $model = new \Model\Company($row);
         $retArr[$row['proposedCode']] = $model;
     }
     return $retArr;
 }
 public function getStats($playerName)
 {
     $playerName = $this->db->escapeString(trim(strtolower($playerName)));
     $result = $this->db->query("SELECT * FROM tntstats WHERE name = '" . $playerName . "'");
     if ($result instanceof \SQLiteResult) {
         $assoc = $result->fetch(SQLITE_ASSOC);
         if (isset($assoc["name"]) and $assoc["name"] === $playerName) {
             return $assoc;
         }
     }
     return null;
 }
Exemple #15
0
 public static function findByPostalCode($postalCode, $countryCode)
 {
     static::initialize();
     $query = 'SELECT * FROM geodb WHERE postalCode = "' . $postalCode . '"';
     if ($countryCode !== NULL) {
         $query .= ' AND countryCode = "' . $countryCode . '"';
     }
     $result = static::$connection->query($query);
     if ($result instanceof \SQLite3Result) {
         return $result->fetchArray(SQLITE3_ASSOC);
     }
     return array();
 }
    /**
     * Create Tables needed for this application.
     *
     * @throws DBException
     *  If a create table query fails.
     */
    protected function createTables()
    {
        $sqls = array(<<<'EOF'
-- Table defining a user.
-- All we store is a hash of the email, so that
-- we can identify the user when he is logging in.
-- Password validation is taken care by google.
CREATE TABLE IF NOT EXISTS users
(
    id INTEGER PRIMARY KEY ASC,
    emailhash TEXT
)
EOF
, <<<'EOF'
-- Table listing all virtual devices that users registrate.
-- Each device belongs to a user and has a human readable name
-- The device id is given by google and is needed
-- to authentificate a device with the playstore.
CREATE TABLE IF NOT EXISTS devices
(
    owner INTEGER,
    name TEXT,
    deviceid TEXT, -- Hex string.

    FOREIGN KEY (owner) REFERENCES user(id)
);
EOF
, <<<'EOF'
-- Table holding records about downloads that get requested.
-- When a user has successfully requested a download the download information
-- will be written into this table and attached to an unique and secure token.
-- The Browser then can start the actual download using this token.
CREATE TABLE IF NOT EXISTS downloads
(
    token TEXT PRIMARY KEY,
    url TEXT, -- The url from where to download.
    marketda TEXT, -- MarketDA Cookie needet for download.
    package TEXT, -- The package the user wants to download.
    expires INTEGER  -- Unix Timestamp when the download information will expire.
);
EOF
);
        foreach ($sqls as $sql) {
            if ($this->db->query($sql) === FALSE) {
                throw new DBException(_('Failed to create tables.'));
            }
        }
    }
Exemple #17
0
 function getConnection()
 {
     if (!$this->connection) {
         $this->connection = $this->openDB();
         // Nahraj databázi
         if (filesize(self::$databasePath) === 0) {
             //$this->beginTransaction();
             $res = $this->connection->query(file_get_contents(__DIR__ . '/setupDB.sql'));
             if (!$res) {
                 throw new InvalidStateException("Can't create SQLite3 database: " . $this->getConnection()->lastErrorMsg());
             }
             //$this->endTransaction();
         }
     }
     return $this->connection;
 }
 /**
  * Cleans entries from journal.
  * @param  array  $conditions
  * @return array of removed items or NULL when performing a full cleanup
  */
 public function clean(array $conditions)
 {
     if (!empty($conditions[Cache::ALL])) {
         $this->database->exec('DELETE FROM CACHE;');
         return;
     }
     $query = array();
     if (!empty($conditions[Cache::TAGS])) {
         $tags = array();
         foreach ((array) $conditions[Cache::TAGS] as $tag) {
             $tags[] = "'" . $this->database->escapeString($tag) . "'";
         }
         $query[] = 'tag IN(' . implode(', ', $tags) . ')';
     }
     if (isset($conditions[Cache::PRIORITY])) {
         $query[] = 'priority <= ' . (int) $conditions[Cache::PRIORITY];
     }
     $entries = array();
     if (!empty($query)) {
         $query = implode(' OR ', $query);
         $result = $this->database->query("SELECT entry FROM cache WHERE {$query}");
         if ($result instanceof SQLiteResult) {
             while ($entry = $result->fetchSingle()) {
                 $entries[] = $entry;
             }
         } else {
             while ($entry = $result->fetchArray(SQLITE3_NUM)) {
                 $entries[] = $entry[0];
             }
         }
         $this->database->exec("DELETE FROM cache WHERE {$query}");
     }
     return $entries;
 }
function handle_admin()
{
    if (empty($_POST['admin_account']) == false && empty($_POST['admin_password']) == false) {
        $account = $_POST['admin_account'];
        $password = md5($_POST['admin_password']);
        //password: ccc95
        $file_path = "../sqlite/books_web.s3db";
        if (file_exists($file_path)) {
            $link = new SQLite3($file_path);
            $sql_cmd = "SELECT password FROM root_account WHERE password='******'";
            $result = $link->query($sql_cmd);
            $i = 0;
            $row = array();
            while ($res = $result->fetchArray(SQLITE3_ASSOC)) {
                $row[$i]['password'] = $res['password'];
                $i++;
            }
            if (count($row) != 0) {
                $_SESSION['root'] = "root";
                return "admin login success.";
            } else {
                return "admin login failed.";
            }
            $link->close();
        } else {
            return "cannot link database.";
        }
    } else {
        return "post error";
    }
}
 /**
  * @return void
  */
 protected function loadAvailablePropertyFields()
 {
     $result = $this->connection->query('PRAGMA table_info(objects);');
     while ($property = $result->fetchArray(SQLITE3_ASSOC)) {
         $this->propertyFieldsAvailable[] = $property['name'];
     }
 }
Exemple #21
0
function check_links()
{
    //Before checking anything, check if laurentian.concat.ca is resolving.
    $catalogue_link = fopen("http://laurentian.concat.ca/", "r");
    if (!$catalogue_link) {
        die("There may be a problem with laurentian.concat.ca so this process is going to halt. If this persists, contact Kevin Beswick");
    }
    fclose($catalogue_link);
    //Check all links from database, if active, leave alone, if not active, delete them.
    $db_session = new SQLite3('reserves.db');
    $query = "SELECT bookbag_id from reserve";
    $results = $db_session->query($query) or die($db_session->lastErrorMsg());
    $begin_link = "http://laurentian.concat.ca/opac/extras/feed/bookbag/opac/";
    $end_link = "?skin=lul";
    $count = 0;
    while ($row = $results->fetchArray()) {
        $file = fopen($begin_link . $row["bookbag_id"] . $end_link, "r");
        if (!$file) {
            //remove from list
            $query = "DELETE from reserve where bookbag_id = " . $row["bookbag_id"];
            $db_session->exec($query) or die("not working... " . $db_session->lastErrorMsg());
            $count++;
        }
        fclose($file);
    }
    echo "Done removing dead links... " . $count . " were removed.";
}
Exemple #22
0
function getCars($query)
{
    $db = new SQLite3('car.db');
    $results = $db->query($query);
    echo "<table class=\"search-results\">";
    echo "<th>Reg nummer</th>";
    echo "<th>Märke</th>";
    echo "<th>Modell</th>";
    echo "<th>Pris</th>";
    echo "<th>Antal mil</th>";
    echo "<th>Årsmodell</th>";
    echo "<th>Redigera</th>";
    $numRows = 0;
    while ($row = $results->fetchArray()) {
        $numRows++;
    }
    if ($numRows === 0) {
        echo "<tr><td colspan=\"8\">Inga resultat för: \"" . $_POST['search'] . "\"</td></tr>";
    } else {
        while ($row = $results->fetchArray()) {
            echo "<tr>\n                <td class=\"car-regnr\"><a data-id=\"{$row['id']}\" href=\"#\" class=\"car-info\">{$row['regnr']}</td>\n                <td class=\"car-brand\">{$row['brand']}</td>\n                <td class=\"car-model\">{$row['model']}</td>\n                <td class=\"car-price\">{$row['price']}</td>\n                <td class=\"car-milage\">{$row['milage']}</td>\n                <td class=\"car-year\">{$row['year']}</td>\n                <td class=\"car-edit-link\"><a data-id=\"{$row['id']}\" href=\"#\" class=\"car-info\">Redigera</a></td>\n                </tr>";
        }
        echo "</table>";
    }
    $db->close();
}
 /**
  * Cleanup cache
  *
  * Check if the current cache size exceeds the given requested cache size.
  * If this is the case purge all cache items from the cache until the cache
  * is only filled up to $rate percentage.
  * 
  * @param int $size 
  * @param flaot $rate 
  * @return void
  */
 public function cleanup($size, $rate)
 {
     // Check if overall cache size exceeds cache limit
     $result = $this->db->query('SELECT SUM( size ) as size FROM metadata');
     $cacheSize = $result->fetchArray(SQLITE3_NUM);
     $cacheSize = $cacheSize[0];
     $result->finalize();
     if ($cacheSize <= $size) {
         // Cache size does not exceed cache value, so we can exit
         // immediately.
         return false;
     }
     // Otherwise clear cache values, until we pass the lower size border
     $maxSize = $size * $rate;
     $result = $this->db->query('SELECT path, size FROM metadata ORDER BY accessed ASC');
     $removed = array();
     do {
         $row = $result->fetchArray(SQLITE3_ASSOC);
         $cacheSize -= $row['size'];
         unlink($this->root . ($removed[] = $row['path']));
     } while ($cacheSize > $maxSize);
     $result->finalize();
     // Remove entries from database
     foreach ($removed as $nr => $value) {
         $removed[$nr] = "'" . $this->db->escapeString($value) . "'";
     }
     $this->db->query('DELETE FROM metadata WHERE path IN ( ' . implode(', ', $removed) . ' )');
 }
Exemple #24
0
 /**
  * Check if cache table exists
  *
  * @return void
  */
 protected function checkTable()
 {
     $tables = [];
     $sql = "SELECT name FROM sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%' " . "UNION ALL SELECT name FROM sqlite_temp_master WHERE type IN ('table', 'view') ORDER BY 1";
     if ($this->isPdo) {
         $sth = $this->sqlite->prepare($sql);
         $sth->execute();
         $result = $sth;
         while (($row = $result->fetch(\PDO::FETCH_ASSOC)) != false) {
             $tables[] = $row['name'];
         }
     } else {
         $result = $this->sqlite->query($sql);
         while (($row = $result->fetchArray(SQLITE3_ASSOC)) != false) {
             $tables[] = $row['name'];
         }
     }
     // If the cache table doesn't exist, create it.
     if (!in_array($this->table, $tables)) {
         $sql = 'CREATE TABLE IF NOT EXISTS "' . $this->table . '" ("id" VARCHAR PRIMARY KEY NOT NULL UNIQUE, "start" INTEGER, "expire" INTEGER, "lifetime" INTEGER, "value" BLOB, "time" INTEGER)';
         if ($this->isPdo) {
             $sth = $this->sqlite->prepare($sql);
             $sth->execute();
         } else {
             $this->sqlite->query($sql);
         }
     }
 }
Exemple #25
0
 public function checkOverlapping($first, $sec, $level)
 {
     if ($level instanceof Level) {
         $level = $level->getName();
     }
     $d = $this->property->query("SELECT * FROM Property WHERE (((startX <= {$first['0']} AND landX >= {$first['0']}) AND (startZ <= {$first['1']} AND landZ >= {$first['1']})) OR ((startX <= {$sec['0']} AND landX >= {$sec['0']}) AND (startZ <= {$first['1']} AND landZ >= {$sec['1']}))) AND level = '{$level}'")->fetchArray(SQLITE3_ASSOC);
     return !is_bool($d);
 }
Exemple #26
0
 public function checkOverlap($startX, $endX, $startZ, $endZ, $level)
 {
     if ($level instanceof Level) {
         $level = $level->getFolderName();
     }
     $result = $this->land->query("SELECT * FROM land WHERE startX <= {$endX} AND endX >= {$endX} AND startZ <= {$endZ} AND endZ >= {$endZ} AND level = '{$level}'")->fetchArray(SQLITE3_ASSOC);
     return !is_bool($result);
 }
Exemple #27
0
 function enableCache($type, $connection, $cache_expire = 600, $table = 'flickr_cache')
 {
     $db = new SQLite3('flickr.db');
     /*
      * If high performance is crucial, you can easily comment
      * out this query once you've created your database table.
      */
     $db->query("\n\t\t\t\tCREATE TABLE IF NOT EXISTS `{$table}` (\n\t\t\t\t\t`request` CHAR( 35 ) NOT NULL ,\n\t\t\t\t\t`response` MEDIUMTEXT NOT NULL ,\n\t\t\t\t\t`expiration` DATETIME NOT NULL ,\n\t\t\t\t\tINDEX ( `request` )\n\t\t\t\t) TYPE = MYISAM");
     if ($db->getOne("SELECT COUNT(*) FROM {$table}") > $this->max_cache_rows) {
         $db->query("DELETE FROM {$table} WHERE expiration < DATE_SUB(NOW(), INTERVAL {$cache_expire} second)");
         $db->query('OPTIMIZE TABLE ' . $this->cache_table);
     }
     $this->cache = 'db';
     $this->cache_db = $db;
     $this->cache_table = $table;
     $this->cache_expire = $cache_expire;
 }
 /**
  * @param $query
  * @return SQLite3Result
  * @throws Ruckusing_Exception
  */
 private function executeQuery($query)
 {
     $SqliteResult = $this->sqlite3->query($query);
     if ($this->isError($SqliteResult)) {
         throw new Ruckusing_Exception(sprintf("Error executing 'query' with:\n%s\n\nReason: %s\n\n", $query, $this->lastErrorMsg()), Ruckusing_Exception::QUERY_ERROR);
     }
     return $SqliteResult;
 }
Exemple #29
0
 /**
  * Run a query on the database;
  * @param string $query
  * @return boolean TRUE on success
  */
 public function query($query)
 {
     $sqlite = new SQLite3($this->path);
     // escape query
     $query = $sqlite->escapeString($query);
     // run it and return result
     return $sqlite->query($query);
 }
Exemple #30
0
 public function findClotheById($id)
 {
     $db = new SQLite3($this->dbFileName);
     $data = $db->query(self::QUERY_BASE . ' WHERE ID_clothes = ' . $id);
     $arrayData = $this->SQLite2JSON($data);
     $db->close();
     return json_encode($arrayData);
 }