Example #1
0
 /**
  * Directly executes SQL
  * @param string $query
  * @return sqlite_result
  * @throws sqlite_exception
  */
 public function exec($query)
 {
     try {
         $query = preg_replace('/`(\\w+)`/is', '"$1"', $query);
         if ($result = $this->con->query($query, SQLITE_BOTH, $error)) {
             return $result;
         } else {
             throw new sqlite_exception($query, $error);
         }
     } catch (Exception $e) {
         throw new sqlite_exception($query, $e->getMessage());
     }
 }
Example #2
0
function open_db()
{
    $db = new SQLiteDatabase("labels.db");
    $q = $db->query('PRAGMA table_info(product)');
    if ($q->numRows() == 0) {
        $db->query('create table product(
				   id integer primary key,
				   title varchar(255),
				   subtitle varchar(255),
				   url varchar(255),
				   sku varchar(32))');
    }
    return $db;
}
Example #3
0
 function getTags($data)
 {
     $db = new SQLiteDatabase('sql/imgorg.db');
     $image = $data->image;
     $q = $db->query('SELECT t.text as text, t.id as id FROM Tags t INNER JOIN Images_Tags it ON t.id = it.tag_id WHERE it.image_id = "' . $image . '"');
     return $q->fetchAll();
 }
Example #4
0
 protected function Query($query)
 {
     //		SPConfig::debOut( $query, false, false, true );
     switch ($this->_driver) {
         case 'SQLITE':
             try {
                 if ($r = $this->_db->query($query, SQLITE_ASSOC)) {
                     $r = $r->fetch();
                 } else {
                     Sobi::Error('cache', sprintf('SQLite error on query: %s', $query), SPC::WARNING, 0, __LINE__, __FILE__);
                     return false;
                 }
             } catch (SQLiteException $x) {
                 Sobi::Error('cache', sprintf('SQLite error: %s', $x->getMessage()), SPC::WARNING, 0, __LINE__, __FILE__);
                 $this->_enabled = false;
                 $this->cleanAll();
                 return false;
             }
             break;
         case 'PDO':
             if ($s = $this->_db->prepare($query)) {
                 $s->execute();
                 $r = $s->fetch(PDO::FETCH_ASSOC);
             } else {
                 Sobi::Error('cache', sprintf('SQLite error on query: %s. Error %s', $query, implode("\n", $this->_db->errorInfo())), SPC::WARNING, 0, __LINE__, __FILE__);
                 $this->_enabled = false;
                 $this->cleanAll();
                 return false;
             }
             break;
     }
     return $r;
 }
Example #5
0
 /**
  * @return bool|SQLiteDatabase
  * @throws Exception
  */
 public function getSqlite()
 {
     // return existing object
     if ($this->_sqlite) {
         return $this->_sqlite;
     }
     // get the database name
     if (!$this->database) {
         $this->database = dirname(dirname(__FILE__)) . '/data/' . get_class($this) . '.db';
     }
     // create the folder
     if (!file_exists(dirname($this->database))) {
         if (!mkdir(dirname($this->database), $this->mode['folder'], true)) {
             return false;
         }
     }
     // connect to the database
     $this->_sqlite = new SQLiteDatabase($this->database, $this->mode['file']);
     if (!$this->_sqlite) {
         throw new Exception(strtr('Unable to create sqlite database for {className}', array('{className}' => get_class($this))));
     }
     // create the table if needed
     if (!$this->_sqlite->query("SELECT name FROM sqlite_master WHERE type='table' AND name='config'")->numRows()) {
         $this->sqlite->queryExec("CREATE TABLE config(config_key text UNIQUE NOT NULL PRIMARY KEY, config_value text)");
     }
     return $this->_sqlite;
 }
Example #6
0
 public function select($filter)
 {
     $sql = "SELECT * FROM {$this->name} WHERE " . $this->filterToSql($filter);
     $res = self::$conn->query($sql);
     if ($res === false) {
         $error = self::$conn->errorInfo();
         switch ($error[0]) {
             case 'HY000':
                 throw new DataStoreNoTableError("Table [{$this->name}] doesn't exists in [{$sql}]");
                 break;
             default:
                 throw new DataStoreError("Error {$error[2]} ({$error[0]}/{$error[1]}) in query {$sql}");
         }
         return false;
     }
     return $res->fetch();
 }
Example #7
0
function createMusicDB()
{
    $dbFileName = "../db/musicDatabase.db";
    if ($db = new SQLiteDatabase($dbFileName)) {
        // first let the engine check table, and create it eventualy
        $q = @$db->query('CREATE TABLE IF NOT EXISTS albums (id int PRIMARY KEY ASC, title TEXT, artist TEXT, cover TEXT, PRIMARY KEY (id))');
    }
}
Example #8
0
 function getAllInfo($data)
 {
     $db = new SQLiteDatabase('sql/imgorg.db');
     $res = $db->query('select * from Albums');
     $json = array();
     while ($o = $res->fetchObject()) {
         $q = $db->query('SELECT * FROM Images WHERE album_id = "' . $o->id . '"');
         $qres = $q->fetchObject();
         if ($qres) {
             $path = $qres->url;
             $o->exif = exif_read_data('../' . $path);
             $o->filename = $qres->filename;
         }
         $o->size = sizeof($q->fetchAll());
         array_push($json, $o);
     }
     return $json;
 }
Example #9
0
function step_1()
{
    if (file_exists(DB_FILE) == true) {
        echo DB_FILE . " already exists, deleted\n";
        unlink(DB_FILE);
    }
    $db = new SQLiteDatabase(DB_FILE);
    return $db->query("CREATE TABLE fuu (" . "\t\t\t id INTEGER PRIMARY KEY," . "\t\t\t insult TEXT," . "\t\t\t audio_file CHAR(255)," . "\t\t\t nb_view INTEGER," . "\t\t\t nb_play INTEGER" . "\t   );");
}
Example #10
0
function getDB()
{
    $dbFile = "filter-demo.db";
    $hasDB = file_exists($dbFile);
    $db = new SQLiteDatabase($dbFile);
    if (!$hasDB) {
        $db->query(readCreateSql());
    }
    return $db;
}
 /**
  * Returns whether or not the key exists and is not expired in the cache,
  * i.e. there is a valid entry for this key
  *
  * @param string $key Cache key associated to the data
  *
  * @return boolean
  */
 public function containsKey($key)
 {
     if (!$this->enabled) {
         return false;
     }
     $result = $this->db->query("SELECT key FROM cache WHERE key='" . $this->key($key) . "' WHERE expire >= datetime('now')");
     $has_key = $result->numRows() > 0;
     $this->Logger->debug("Cache contains {$key}? " . $has_key ? 'TRUE' : 'FALSE');
     return $has_key;
 }
Example #12
0
 private function action()
 {
     if ($db = new SQLiteDatabase(_MINDSRC_ . '/mind3rd/SQLite/mind')) {
         $result = $db->query("SELECT * FROM user where login='******' AND pwd='" . sha1($this->pwd) . "' AND status= 'A'");
         $row = false;
         while ($result->valid()) {
             $row = $result->current();
             $_SESSION['auth'] = JSON_encode($row);
             $_SESSION['login'] = $row['login'];
             break;
         }
         if (!$row) {
             Mind::write('auth_fail', true);
             return false;
         }
     } else {
         die('Database not found!');
     }
     return $this;
 }
Example #13
0
function hitcounter($url)
{
    //error_reporting(6143);
    $hits = 0;
    if ($db = new SQLiteDatabase('/home/a3253051/db/hitcounter.db')) {
        $q = @$db->query("SELECT counter FROM rsshits WHERE url = '" . $url . "'");
        if ($q === false) {
            $db->queryExec('CREATE TABLE rsshits (url TEXT, counter int)');
            //$hits = 1;
        } else {
            $result = $q->fetchSingle();
            $hits = intval($result);
            //$db->queryExec("INSERT INTO rsshits VALUES ('".$_GET['url']."',".$hits.")");
            //$db->queryExec("UPDATE rsshits SET counter=".$hits." WHERE url='".$_GET['url']."'");
        }
    } else {
        die($err);
    }
    return $hits;
}
Example #14
0
 function getInfo($data)
 {
     $db = new SQLiteDatabase("sql/imgorg.db");
     $image = $data->image;
     $q = $db->query('SELECT url FROM Images WHERE id = "' . $image . '"');
     $path = $q->fetchObject()->url;
     $ret = exif_read_data('../' . $path);
     return $ret;
 }
Example #15
0
        $width = $argv[3];
    }
} else {
    if (isset($_GET['sura']) && is_numeric($_GET['sura']) && isset($_GET['ayah']) && is_numeric($_GET['ayah'])) {
        $sura = $_GET['sura'];
        $ayah = $_GET['ayah'];
        if (isset($_GET['width']) && is_numeric($_GET['width'])) {
            $width = $_GET['width'];
        }
    }
}
$db = new SQLiteDatabase('./data/sura_ayah_page_text.sqlite2.db');
if (!$db) {
    die("died");
}
$q = @$db->query("select page, text from sura_ayah_page_text where sura = {$sura} and ayah = {$ayah}");
$result = $q->fetch();
$page = $result[page];
$text = $result[text];
if ($page == 1 || $page == 2) {
    $fontSize = 32;
} else {
    $fontSize = 24;
}
//$fontSize = 1.6*$fontSize; // seems to overflow i.e. wrapping isn't perfect
$font = './data/fonts/QCF_P' . sprintf('%03d', $page) . '.TTF';
$words = split(';', $text);
$i = 0;
$max = count($words) - 1;
$min = 7;
$ayahText = array();
Example #16
0
<?php

/* open connection to memory database */
$db = new SQLiteDatabase(":memory:");
/* execute a regular query */
$db->query("CREATE TABLE test(a,b)");
$db->query("INSERT INTO test VALUES('1','2')");
/* retrieve data using an unbuffered query */
$r = $db->unbufferedQuery("SELECT * FROM test", SQLITE_ASSOC);
echo '<pre>';
/* use object iterators to retrieve the data, without any additional functions */
foreach ($r as $row) {
    print_r($row);
}
echo '</pre>';
Example #17
0
<?php

// open database
$db = new SQLiteDatabase("./ip.db");
// begin transaction
$db->query("BEGIN");
$fp = fopen("./ip-to-country.csv", "r");
$query_str = '';
while ($row = fgetcsv($fp, 4096)) {
    foreach ($row as $key => $val) {
        // secure data
        $row[$key] = sqlite_escape_string($val);
    }
    // check for existance of a country in db
    if (!($country_id = $db->singleQuery("SELECT id FROM country_data WHERE cc_code_2='{$row[2]}'"))) {
        // add new country
        if (!$db->query("INSERT INTO country_data \n\t\t\t(cc_code_2, cc_code_3, country_name) \n\t\t\tVALUES('{$row[2]}', '{$row[3]}', '{$row[4]}')")) {
            // fetch error
            $err_code = $db->lastError();
            printf("Query Failed %d:%s\n", $err_code, sqlite_error_string($err_code));
            exit;
        }
        // get ID for the last inserted row
        $country_id = $db->lastInsertRowid();
    }
    $query_str .= "INSERT INTO ip_ranges \n\t\t\t(ip_start, ip_end, country_code)\n\t\t\tVALUES({$row[0]}, {$row[1]}, {$country_id});";
}
// insert IP data via a chained query
$db->query($query_str);
// finalize transaction
$db->query("COMMIT");
    try {
        $db = new SQLiteDatabase($dbFile, 0666, $error);
        $db->query("BEGIN;\n\t\t\tCREATE TABLE aloha (\n\t\t\t\tid INTEGER PRIMARY KEY,\n\t\t\t\tpageId CHAR(255),\n\t\t\t\tcontentId CHAR(255),\n\t\t\t\tcontent TEXT\n\t\t\t);\n\n\t\t\tINSERT INTO aloha \n\t\t\t\t(id, pageId, contentId, content)\n\t\t\tVALUES\n\t\t\t\t(NULL, NULL, NULL, 'Click to edit');\n\n\t\t\tCOMMIT;");
        error_log("\n" . 'SQLite Database created ' . $dbFile, 3, "demo-app.log");
    } catch (Exception $e) {
        die($error);
    }
} else {
    // db already exists
    $db = new SQLiteDatabase($dbFile, 0666, $error);
}
// check if we have already a data set for this and save data
// XSS handling required
$pageId = sqlite_escape_string($_REQUEST['pageId']);
$query = "SELECT * FROM aloha \n\tWHERE\n\t\tpageId = '" . $pageId . "';";
$result = $db->query($query, $error);
$exists = false;
$data = array();
while ($result->valid()) {
    $exists = true;
    $row = $result->current();
    $data[] = $row;
    $result->next();
    error_log("\n" . 'data available for page ' . $pageId, 3, "demo-app.log");
}
error_log("\n" . 'error: ' . print_r($data, true), 3, "demo-app.log");
if (!empty($error)) {
    error_log("\n" . 'error: ' . print_r($error, true), 3, "demo-app.log");
} else {
    print_r(json_encode($data));
}
Example #19
0
<!DOCTYPE html>
			<html>
<?php 
$sqlitedb = new SQLiteDatabase('mydb.sqli');
$sqlReturn = $sqlitedb->query("SELECT * FROM members WHERE name = \"John\"");
Example #20
0
#
$is_admin = false;
$links = array();
if ($db = new SQLiteDatabase('links')) {
    #
    # If a new link is being entered, insert it into the DB.
    #
    if ($_GET['save'] && $is_admin) {
        #
        # Insert the row.
        #
        $url = sqlite_escape_string($_GET['save']);
        $title = isset($_GET['title']) ? sqlite_escape_string($_GET['title']) : '';
        $key = '';
        $now = time();
        $q = $db->query('INSERT INTO links (url, title, created, last_access) VALUES ("' . $url . '", "' . $title . '", ' . $now . ', ' . $now . ')');
        if ($q === false) {
            create_table($db);
            $db->query('INSERT INTO links (url, title, created, last_access) VALUES ("' . $url . '", "' . $title . '", ' . $now . ', ' . $now . ')');
        }
        #
        # Create the key.
        #
        $id = $db->lastInsertRowid();
        $key = encode_key($id, $codeset);
        $db->query('UPDATE links SET key="' . $key . '" WHERE id=' . $id);
        #
        # Get the title.
        #
        if ($title === '') {
            $lines = array();
Example #21
0
$invoice_id = intval($_GET['invoice_id']);
$product_url = '';
$price_in_usd = 0;
$price_in_btc = 0;
$amount_paid_btc = 0;
$amount_pending_btc = 0;
try {
    //create or open the database
    $database = new SQLiteDatabase('db.sqlite', 0666, $error);
} catch (Exception $e) {
    die($error);
}
//find the invoice form the database
$query = "select price_in_usd, product_url, price_in_btc from Invoices where invoice_id = {$invoice_id}";
if ($result = $database->query($query, SQLITE_BOTH, $error)) {
    if ($row = $result->fetch()) {
        $product_url = $row['product_url'];
        $price_in_usd = $row['price_in_usd'];
        $price_in_btc = $row['price_in_btc'];
    } else {
        die('Invoice not found');
    }
} else {
    die($error);
}
//find the pending amount paid
$query = "select SUM(value) as value from pending_invoice_payments where invoice_id = {$invoice_id}";
if ($result = $database->query($query, SQLITE_BOTH, $error)) {
    if ($row = $result->fetch()) {
        $amount_pending_btc = $row['value'];
Example #22
0
<?php

$list = <<<EOF
AD,Andorra;AE,United Arab Emirates;AF,Afghanistan;AG,Antigua & Barbuda;AI,Anguilla;AL,Albania;AM,Armenia;AN,Netherlands Antilles;AO,Angola;AQ,Antarctica;AR,Argentina;AS,American Samoa;AT,Austria;AU,Australia;AW,Aruba;AZ,Azerbaijan;BA,Bosnia and Herzegovina;BB,Barbados;BD,Bangladesh;BE,Belgium;BF,Burkina Faso;BG,Bulgaria;BH,Bahrain;BI,Burundi;BJ,Benin;BM,Bermuda;BN,Brunei Darussalam;BO,Bolivia;BR,Brazil;BS,Bahama;BT,Bhutan;BU,Burma (no longer exists);BV,Bouvet Island;BW,Botswana;BY,Belarus;BZ,Belize;CA,Canada;CC,Cocos (Keeling) Islands;CF,Central African Republic;CG,Congo;CH,Switzerland;CI,Côte D'ivoire (Ivory Coast);CK,Cook Iislands;CL,Chile;CM,Cameroon;CN,China;CO,Colombia;CR,Costa Rica;CS,Czechoslovakia (no longer exists);CU,Cuba;CV,Cape Verde;CX,Christmas Island;CY,Cyprus;CZ,Czech Republic;DD,German Democratic Republic (no longer exists);DE,Germany;DJ,Djibouti;DK,Denmark;DM,Dominica;DO,Dominican Republic;DZ,Algeria;EC,Ecuador;EE,Estonia;EG,Egypt;EH,Western Sahara;ER,Eritrea;ES,Spain;ET,Ethiopia;FI,Finland;FJ,Fiji;FK,Falkland Islands (Malvinas);FM,Micronesia;FO,Faroe Islands;FR,France;FX,France, Metropolitan;GA,Gabon;GB,United Kingdom (Great Britain);GD,Grenada;GE,Georgia;GF,French Guiana;GH,Ghana;GI,Gibraltar;GL,Greenland;GM,Gambia;GN,Guinea;GP,Guadeloupe;GQ,Equatorial Guinea;GR,Greece;GS,South Georgia and the South Sandwich Islands;GT,Guatemala;GU,Guam;GW,Guinea-Bissau;GY,Guyana;HK,Hong Kong;HM,Heard & McDonald Islands;HN,Honduras;HR,Croatia;HT,Haiti;HU,Hungary;ID,Indonesia;IE,Ireland;IL,Israel;IN,India;IO,British Indian Ocean Territory;IQ,Iraq;IR,Islamic Republic of Iran;IS,Iceland;IT,Italy;JM,Jamaica;JO,Jordan;JP,Japan;KE,Kenya;KG,Kyrgyzstan;KH,Cambodia;KI,Kiribati;KM,Comoros;KN,St. Kitts and Nevis;KP,Korea, Democratic People's Republic of;KR,Korea, Republic of;KW,Kuwait;KY,Cayman Islands;KZ,Kazakhstan;LA,Lao People's Democratic Republic;LB,Lebanon;LC,Saint Lucia;LI,Liechtenstein;LK,Sri Lanka;LR,Liberia;LS,Lesotho;LT,Lithuania;LU,Luxembourg;LV,Latvia;LY,Libyan Arab Jamahiriya;MA,Morocco;MC,Monaco;MD,Moldova, Republic of;MG,Madagascar;MH,Marshall Islands;ML,Mali;MN,Mongolia;MM,Myanmar;MO,Macau;MP,Northern Mariana Islands;MQ,Martinique;MR,Mauritania;MS,Monserrat;MT,Malta;MU,Mauritius;MV,Maldives;MW,Malawi;MX,Mexico;MY,Malaysia;MZ,Mozambique;NA,Namibia;NC,New Caledonia;NE,Niger;NF,Norfolk Island;NG,Nigeria;NI,Nicaragua;NL,Netherlands;NO,Norway;NP,Nepal;NR,Nauru;NT,Neutral Zone (no longer exists);NU,Niue;NZ,New Zealand;OM,Oman;PA,Panama;PE,Peru;PF,French Polynesia;PG,Papua New Guinea;PH,Philippines;PK,Pakistan;PL,Poland;PM,St. Pierre & Miquelon;PN,Pitcairn;PR,Puerto Rico;PT,Portugal;PW,Palau;PY,Paraguay;QA,Qatar;RE,Réunion;RO,Romania;RU,Russian Federation;RW,Rwanda;SA,Saudi Arabia;SB,Solomon Islands;SC,Seychelles;SD,Sudan;SE,Sweden;SG,Singapore;SH,St. Helena;SI,Slovenia;SJ,Svalbard & Jan Mayen Islands;SK,Slovakia;SL,Sierra Leone;SM,San Marino;SN,Senegal;SO,Somalia;SR,Suriname;ST,Sao Tome & Principe;SU,Union of Soviet Socialist Republics (no longer exists);SV,El Salvador;SY,Syrian Arab Republic;SZ,Swaziland;TC,Turks & Caicos Islands;TD,Chad;TF,French Southern Territories;TG,Togo;TH,Thailand;TJ,Tajikistan;TK,Tokelau;TM,Turkmenistan;TN,Tunisia;TO,Tonga;TP,East Timor;TR,Turkey;TT,Trinidad & Tobago;TV,Tuvalu;TW,Taiwan, Province of China;TZ,Tanzania, United Republic of;UA,Ukraine;UG,Uganda;UM,United States Minor Outlying Islands;US,United States of America;UY,Uruguay;UZ,Uzbekistan;VA,Vatican City State (Holy See);VC,St. Vincent & the Grenadines;VE,Venezuela;VG,British Virgin Islands;VI,United States Virgin Islands;VN,Viet Nam;VU,Vanuatu;WF,Wallis & Futuna Islands;WS,Samoa;YD,Democratic Yemen (no longer exists);YE,Yemen;YT,Mayotte;YU,Yugoslavia;ZA,South Africa;ZM,Zambia;ZR,Zaire;ZW,Zimbabwe;ZZ,Unknown or unspecified country
EOF;
if ($db = new SQLiteDatabase('test.db')) {
    $q = @$db->query('SELECT * FROM countries LIMIT 0,1;');
    if ($q === false) {
        $l = split(';', $list);
        $db->queryExec('CREATE TABLE countries (id int, code char, name char, PRIMARY KEY (id));');
        foreach ($l as $k => $v) {
            $tmp = split(',', $v);
            $db->queryExec(sprintf('INSERT INTO countries VALUES (%s, "%s", "%s");', $k, $tmp[0], $tmp[1]));
        }
    }
} else {
    die($err);
}
define('_HYGRID_TABLE_', 'countries');
define('_HYGRID_ALLOWED_TABLES', 'countries');
class hygrid
{
    static $page, $rpp, $rows;
    function __construct()
    {
        $this->total = 0;
        $this->table = $_REQUEST['table'] ? $_REQUEST['table'] : _HYGRID_TABLE_;
        $this->page = $_REQUEST['page'] ? $_REQUEST['page'] : 1;
        $this->rpp = $_REQUEST['rpp'] ? $_REQUEST['rpp'] : false;
        // total
    }
<?php

/**
 * Инициализация структуры и данных БД.
 *
 * @author Sergey S. Nevmerzhitsky (http://koteg.moikrug.ru/), 25.01.2012
 * @since 25.01.2012
 */
$resource = new SQLiteDatabase(dirname(__FILE__) . '/../data/test.sqlite', 0666, $error);
if (empty($resource)) {
    die("Cannot connect: {$error}");
}
$sqls = array();
//$sqls[] = 'DROP TABLE foobar';
$sqls[] = <<<SQL
CREATE TABLE foobar (
  id   INTEGER PRIMARY KEY ASC,
  name TEXT NOT NULL,
  foo  TEXT NOT NULL,
  bar  TEXT NOT NULL
)
SQL;
foreach ($sqls as $sql) {
    /* @var $result SQLiteResult */
    $result = $resource->query($sql, SQLITE_ASSOC, $error);
    if (!$result) {
        die("Cannot execute query: {$error}");
    }
}
Example #24
0
File: sqlite.php Project: jyip/ToDo
<?php

$tasks_db = 'tasks.db';
define('CREATE_TASKS_SQL', "CREATE TABLE tasks (\n\t\t\tid integer primary key,\n\t\t\tparent_id integer not null,\n\t\t\ttask text not null,\n\t\t\tcreated_at datetime not null,\n\t\t\tcompleted_at datetime)");
define('CHECK_FOR_EXISTING_TASKS_TABLE_SQL', "SELECT name FROM sqlite_master\n\t\t WHERE type = 'table'\n\t\t AND name = 'tasks'");
define('CREATE_IMAGES_SQL', "CREATE table images (\n\t\t id integer primary key,\n\t\t name text not null,\n\t\t directory text not null,\n\t\t title text,\n\t\t created_at datetime,\n\t\t created_by text,\n\t\t caption text)");
/**
 * Open the database or create if it does not exist
 */
$sqlite = new SQLiteDatabase($tasks_db);
// Does table exist?
$res = @$sqlite->query(CHECK_FOR_EXISTING_TASKS_TABLE_SQL);
// If not then create it
if (!$res->numRows()) {
    @$sqlite->query(CREATE_TASKS_SQL);
}
/*
function table_exists($dbhandle,$table) 
{
	$sql = "SELECT * FROM sqlite_master
			WHERE type='table'
			AND name='". $sqlite_escape_string($table) . "'";
			
	$res = $dbc->query($sql);
	if($res->numRows()) {
		return true;
	}
	return false;
} */
Example #25
0
    mkdir('stats');
}
include 'config.inc.php';
// Check for compatibility
if (!version_compare(PHP_VERSION, '5.0.0', '>=')) {
    die("I need PHP version 5 or greater!\n");
}
if (!class_exists('SQLiteDatabase')) {
    die("Cannot find PHP-SQLite extension!\n");
}
if (!file_exists(PWS_DATABASE)) {
    die("The database file was not found!\n");
}
$db = new SQLiteDatabase(PWS_DATABASE);
/////////////////////// ENCRYPTED
$protected = $db->query('SELECT encrypted FROM accesspoints WHERE encrypted = 1')->numRows();
$unprotected = $db->query('SELECT encrypted FROM accesspoints WHERE encrypted = 0')->numRows();
$total = $protected + $unprotected;
$part_p = $protected / $total;
$part_u = $unprotected / $total;
$arc_p = $part_p * 360;
$arc_u = $part_u * 360;
$image = imagecreatetruecolor(380, 202);
// allocate some solors
$white = imagecolorallocate($image, 0xff, 0xff, 0xff);
$darkred = imagecolorallocate($image, 0x99, 0x0, 0x0);
$darkgreen = imagecolorallocate($image, 0x0, 0x99, 0x0);
imagefill($image, 0, 0, $white);
imagefilledarc($image, 100, 100, 200, 200, 0, $arc_p, $darkred, IMG_ARC_PIE);
imagefilledarc($image, 100, 100, 200, 200, $arc_p, 360, $darkgreen, IMG_ARC_PIE);
imagestring($image, 2, 220, 10, 'unprotected accesspoints', $darkgreen);
Example #26
0
$dbhandle = sqlite_open('sqlitedb');
sqlite_close($dbhandle);
if ($db = sqlite_open('mysqlitedb', 0666, $sqliteerror)) {
    sqlite_query($db, 'CREATE TABLE foo (bar varchar(10))');
    sqlite_query($db, "INSERT INTO foo VALUES ('fnord')");
    $result = sqlite_query($db, 'select bar from foo');
    var_dump(sqlite_fetch_array($result));
} else {
    die($sqliteerror);
}
$db = sqlite_open('mysqlitedb');
$result = sqlite_query($db, "SELECT * FROM mytable WHERE name='John Doe'");
$rows = sqlite_num_rows($result);
echo "Number of rows: {$rows}";
$db = new SQLiteDatabase('mysqlitedb');
$result = $db->query("SELECT * FROM mytable WHERE name='John Doe'");
$rows = $result->numRows();
echo "Number of rows: {$rows}";
$dbhandle = sqlite_open('mysqlitedb');
$query = sqlite_exec($dbhandle, "UPDATE users SET email='*****@*****.**' WHERE username='******'", $error);
if (!$query) {
    exit("Error in query: '{$error}'");
} else {
    echo 'Number of rows modified: ', sqlite_changes($dbhandle);
}
$dbhandle = new SQLiteDatabase('mysqlitedb');
$query = $dbhandle->queryExec("UPDATE users SET email='*****@*****.**' WHERE username='******'", $error);
if (!$query) {
    exit("Error in query: '{$error}'");
} else {
    echo 'Number of rows modified: ', $dbhandle->changes();
Example #27
0
 public static function setUpDbSqlLite()
 {
     // create new database (OO interface)
     $db = new SQLiteDatabase("data/db.sqlite");
     // create table foo and insert sample data
     $db->query("BEGIN;\n\t\t\t\tCREATE TABLE IF NOT EXISTS short_urls(id INTEGER PRIMARY KEY AUTOINCRIMENT, long_url CHAR(255), short_url CHAR(100), date_created DATETIME);\n\t\t\t\tINSERT INTO short_urls (long_url, short_url, date_created) VALUES('http://example.com/long','http://example.com/short', '2009-10-20 00:00:00');\n\t\t\t\tCOMMIT;");
     // execute a query
     $result = $db->query("SELECT * FROM short_urls");
     // iterate through the retrieved rows
     while ($result->valid()) {
         // fetch current row
         $row = $result->current();
         print_r($row);
         // proceed to next row
         $result->next();
     }
     // not generally needed as PHP will destroy the connection
     unset($db);
 }
Example #28
0
            id INTEGER PRIMARY KEY,
            text STRING
        );
        INSERT INTO Tags (text) VALUES("Family");
        INSERT INTO Tags (text) VALUES("Friends");
        INSERT INTO Tags (text) VALUES("Other")');
    // Images
    //        $db->queryExec('DROP TABLE Images');
    $db->queryExec('CREATE TABLE Images (
            id INTEGER PRIMARY KEY,
            filename STRING,
            url STRING,
            album_id INTEGER,
            description TEXT
        )');
    //        $dir = "../../images/thumbs/";
    //        $images = array();
    //        $d = dir($dir);
    //        $i = 0;
    //        while($name = $d->read()){
    //            if(!preg_match('/\.(jpg|gif|png)$/', $name)) continue;
    //            $size = filesize($dir.$name);
    //            $lastmod = filemtime($dir.$name)*1000;
    //            $db->queryExec('INSERT INTO Images (filename, url) VALUES
    //                ("'.$name.'","images/thumbs/'.$name.'")');
    //        }
    //        $d->close();
    echo json_encode($db->query('select * from Images')->fetchAll());
} else {
    die($err);
}
include "config.php";
// Include the class
include "class.php";
// Initiate database
if ($preferredDatabase == "sqlite") {
    $db = new SQLiteDatabase("db.sqlite");
} elseif ($preferredDatabase == "mysql") {
    $socket = mysql_connect($mysqlHost, $mysqlUsername, $mysqlPassword) or die(mysql_error());
    mysql_select_db($mysqlDatabase, $socket);
}
// If the form has not been submitted
if (!isset($_GET['submit'])) {
    echo "<form method=\"GET\">\r\n\t\t\t\t<table>\r\n\t\t\t\t<tr><td>Plugin's exact name:</td><td><input type=\"text\" name=\"name\" value=\"" . $_GET['name'] . "\" /></td></tr>\r\n\t\t\t\t<tr><td>Plugin's forum URL:</td><td><input type=\"text\" name=\"url\" /></td></tr>\r\n\t\t\t\t<tr><td><input type=\"submit\" name=\"submit\" /></td></tr>\r\n\t\t\t\t</table>\r\n\t\t\t</form>";
} else {
    // Secure the input
    $name = secure_sql_input($_GET['name']);
    $url = secure_sql_input($_GET['url']);
    // Check whether the URL has the https protocol
    if (substr_count($url, "https", 0, 5) > 0) {
        // If it does have the https protocol we need to ensure it gets changed
        $url = preg_replace("/https/i", "http", $url);
    }
    // Insert the URL into a new row in the database along with the name of the plugin
    $sql = "INSERT INTO plugins (name, url) VALUES ('" . $name . "', '" . $url . "')";
    if ($preferredDatabase == "sqlite") {
        $db->query($sql);
    } elseif ($preferredDatabase == "mysql") {
        mysql_query($sql, $socket);
    }
    echo "<p>Plugin URL added, please <a href=\"plugins.php\">re-run the updater</a>!";
}
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
// Set the script execution limit
set_time_limit("120");
// Initiate the database
if ($preferredDatabase == "sqlite") {
    $db = new SQLiteDatabase("db.sqlite");
} elseif ($preferredDatabase == "mysql") {
    $socket = mysql_connect($mysqlHost, $mysqlUsername, $mysqlPassword) or die(mysql_error());
    mysql_select_db($mysqlDatabase, $socket);
}
// Get a list of all plugins which already have a forum URL associated with them
$database = array();
$sql = "SELECT * FROM plugins";
if ($preferredDatabase == "sqlite") {
    $query = $db->query($sql);
    while ($query->valid()) {
        $database[] = $query->current();
        // Move pointer to next row
        $query->next();
    }
} elseif ($preferredDatabase == "mysql") {
    $query = mysql_query($sql, $socket);
    while ($row = mysql_fetch_array($query)) {
        $database[] = $row;
    }
}
$Iplugins = array();
// For each entry in the database, grab its corresponding array
foreach ($database as $id => $array) {
    // For each one of these arrays, get the type (name of column) and its value