当前位置: 首页>>代码示例>>PHP>>正文


PHP PDO::query方法代码示例

本文整理汇总了PHP中PDO::query方法的典型用法代码示例。如果您正苦于以下问题:PHP PDO::query方法的具体用法?PHP PDO::query怎么用?PHP PDO::query使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在PDO的用法示例。


在下文中一共展示了PDO::query方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: add_member

function add_member($username, $password)
{
    require 'password.php';
    try {
        define('DB_HOST', getenv('OPENSHIFT_MYSQL_DB_HOST'));
        define('DB_PORT', getenv('OPENSHIFT_MYSQL_DB_PORT'));
        define('DB_USER', getenv('OPENSHIFT_MYSQL_DB_USERNAME'));
        define('DB_PASS', getenv('OPENSHIFT_MYSQL_DB_PASSWORD'));
        define('DB_NAME', getenv('OPENSHIFT_GEAR_NAME'));
        try {
            $dsn = 'mysql:dbname=members;host=' . DB_HOST . ';port=' . DB_PORT;
            $db = new PDO($dsn, DB_USER, DB_PASS);
        } catch (PDOException $ex) {
            echo 'Error!: ' . $ex->getMessage();
            die;
        }
        $password = password_hash($password, PASSWORD_BCRYPT);
        echo $password;
        $query = $db->query("USE members");
        $query = $db->query("INSERT INTO members (username, password) VALUES ('{$username}', '{$password}')");
        header('Location: main_login.php');
        return TRUE;
    } catch (Exception $ex) {
        return FALSE;
    }
}
开发者ID:jcomish,项目名称:Web2,代码行数:26,代码来源:model.php

示例2: testEquipmentUpdate

 public function testEquipmentUpdate()
 {
     $this->delete($this->insert(array(Object::TIME_IN_SECONDS => 3600, Object::DISTANCE => 12, Object::SHOEID => 1)));
     $this->delete($this->insert(array(Object::TIME_IN_SECONDS => 3600, Object::DISTANCE => 12, Object::SHOEID => 2)));
     $this->assertEquals(array('km' => 10, 'time' => 3000), $this->PDO->query('SELECT `km`, `time` FROM `' . PREFIX . 'shoe` WHERE `id`=1 AND `accountid`=0')->fetch(PDO::FETCH_ASSOC));
     $this->assertEquals(array('km' => 0, 'time' => 0), $this->PDO->query('SELECT `km`, `time` FROM `' . PREFIX . 'shoe` WHERE `id`=2 AND `accountid`=0')->fetch(PDO::FETCH_ASSOC));
 }
开发者ID:schoch,项目名称:Runalyze,代码行数:7,代码来源:DeleterTest.php

示例3: init_db

function init_db($db_file_name)
{
    global $db;
    $need_init_db = !file_exists($db_file_name);
    $dsn = 'sqlite:' . $db_file_name;
    $db = new PDO($dsn);
    if (!$db) {
        die('failed to open sqlite.');
    }
    if ($need_init_db) {
        $sql = <<<SQL
create table pages (
  id integer primary key,
  title varchar(255) unique,
  body text,
  created_at timestamp default current_timestamp,
  updated_at timestamp default current_timestamp
)
SQL;
        $result = $db->query($sql);
        $sql = <<<SQL
insert into pages
    (id, title, body)
  values
    (1, 'index', '...')
SQL;
        $result = $db->query($sql);
    }
}
开发者ID:jugyo,项目名称:piki,代码行数:29,代码来源:index.php

示例4: setDefaultAttributes

 /**
  * Setting default values on the PDO instance like errormode, encoding and
  * so on.
  */
 public function setDefaultAttributes()
 {
     $this->_pdo->setAttribute(\PDO::ATTR_CASE, \PDO::CASE_NATURAL);
     $this->_pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
     $this->_pdo->setAttribute(\PDO::ATTR_ORACLE_NULLS, \PDO::NULL_TO_STRING);
     $this->_pdo->query("SET NAMES utf8");
 }
开发者ID:sclib,项目名称:database,代码行数:11,代码来源:Database.php

示例5: optimizeDB

function optimizeDB($text)
{
    global $pathToIndex;
    // SETTING BEGIN
    // Run the task every n days
    $scheduleDays = 10;
    // SETTING END
    $loggixDB = $pathToIndex . Loggix_Core::LOGGIX_SQLITE_3;
    $filename = $loggixDB . '.BAK';
    if (!file_exists($filename) || filemtime($filename) + 86400 * $scheduleDays <= time()) {
        if (copy($loggixDB, $filename)) {
            chmod($filename, 0666);
            $backupDB = 'sqlite:' . $filename;
            $bdb = new PDO($backupDB);
            // Garbage Collection (/admin/delete.php)
            $maxLifeTime = get_cfg_var("session.gc_maxlifetime");
            $expirationTime = time() - $maxLifeTime;
            $sql = 'DELETE FROM ' . SESSION_TABLE . ' ' . 'WHERE ' . "sess_date < '" . $expirationTime . "'";
            $bdb->query($sql);
            // Vacuum DB
            $bdb->query('VACUUM');
            if (rename($loggixDB, $loggixDB . '.OLD')) {
                copy($filename, $loggixDB);
                chmod($loggixDB, 0666);
            }
            if (file_exists($loggixDB)) {
                unlink($loggixDB . '.OLD');
            }
        }
    }
    return $text;
}
开发者ID:hijiri,项目名称:optimizeDB,代码行数:32,代码来源:optimizeDB.php

示例6: pickUserData

 /**
  * Вынимает данные пользователя из БД
  * @param mixed $sourceUserId ИД пользователя или его логин
  */
 public function pickUserData($sourceUserId)
 {
     // Подключаем базу - источник
     $this->_debugMessage("Connecting to source database ...");
     $dsn = "mysql:dbname={$this->_sourceDb['dbname']};";
     $dsn .= "host={$this->_sourceDb['host']}";
     $db = new PDO($dsn, $this->_sourceDb['user'], $this->_sourceDb['pass'], array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''));
     $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     $result = $db->query("SELECT id FROM users\n            WHERE id = '{$sourceUserId}' OR user_login = '{$sourceUserId}' LIMIT 1");
     $sourceUserId = $result->fetchColumn();
     $tablesSelected = array();
     // Делаем выборку таблиц и их данных из массива
     $this->_debugMessage("Selecting tables ...");
     foreach ($this->_tablesTemplate as $table => $params) {
         if (!isset($params['userId']) && !isset($params['selectCase'])) {
             die('Can\'t select table without key or `where` statement!');
         }
         $sql = 'select * from `' . $table . '` where ';
         $sql .= isset($params['selectCase']) ? str_ireplace('{$userId}', $sourceUserId, $params['selectCase']) : " `{$params['userId']}`={$sourceUserId};";
         $result = $db->query($sql);
         $tablesSelected[$table] = $result->fetchAll(PDO::FETCH_ASSOC);
         $this->_debugMessage("`{$table}` selected;");
     }
     return $tablesSelected;
 }
开发者ID:ru-easyfinance,项目名称:EasyFinance,代码行数:29,代码来源:generateUsers.php

示例7: initialize

    /**
     * @inheritdoc
     */
    public function initialize()
    {
        $createPhotoTable = <<<SQL
CREATE TABLE IF NOT EXISTS "photo" (
    "uuid" TEXT NOT NULL PRIMARY KEY,
    "resourceId" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    "httpUrl" TEXT NOT NULL,
    "position" INT NOT NULL,
    "filePath" TEXT
)
SQL;
        $this->pdo->query($createPhotoTable);
        $createAlternativeTextTable = <<<SQL
CREATE TABLE IF NOT EXISTS "alternative_text" (
    "photo_uuid" TEXT NOT NULL,
    "alt" TEXT NOT NULL,
    "lang" TEXT NOT NULL,
    FOREIGN KEY(photo_uuid) REFERENCES photo(uuid)
)
SQL;
        $this->pdo->query($createAlternativeTextTable);
        $this->pdo->query("CREATE INDEX resource ON \"photo\" (resourceId);");
        $this->pdo->query("CREATE INDEX fk_alt_photo_uuid ON \"alternative_text\" (photo_uuid);");
    }
开发者ID:caminalab,项目名称:phphotosuite,代码行数:28,代码来源:SqlitePhotoRepository.php

示例8: getSQLiteDB

    static function getSQLiteDB()
    {
        if (file_exists(SABRE_TEMPDIR . '/testdb.sqlite')) {
            unlink(SABRE_TEMPDIR . '/testdb.sqlite');
        }
        $pdo = new PDO('sqlite:' . SABRE_TEMPDIR . '/testdb.sqlite');
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $pdo->query('
CREATE TABLE calendarobjects ( 
	id integer primary key asc, 
    calendardata text, 
    uri text, 
    calendarid integer, 
    lastmodified integer
);
');
        $pdo->query('
CREATE TABLE calendars (
    id integer primary key asc, 
    principaluri text, 
    displayname text, 
    uri text,
    ctag integer,
    description text,
	calendarorder integer,
    calendarcolor text,
    timezone text,
    components text
);');
        $pdo->query('INSERT INTO calendars (principaluri,displayname,uri,description,calendarorder,calendarcolor,components) 
            VALUES ("principals/user1","user1 calendar","UUID-123467","Calendar description", "1", "#FF0000","VEVENT,VTODO");');
        $stmt = $pdo->prepare('INSERT INTO calendarobjects (calendardata, uri, calendarid, lastmodified) VALUES (?, "UUID-2345", 1, DATETIME("NOW"))');
        $stmt->execute(array(self::getTestCalendarData()));
        return $pdo;
    }
开发者ID:Gninety,项目名称:Microweber,代码行数:35,代码来源:TestUtil.php

示例9: getItems4Client

function getItems4Client()
{
    $DB = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USERNAME, DB_PASSWORD);
    $table = DB_TABLE;
    //检查一下是否存在表
    $sql = "SHOW TABLES LIKE '%{$table}%';";
    $rc = $DB->query($sql)->rowCount();
    if (!$rc) {
        $sqlFile = file_get_contents('items.sql');
        $DB->exec($sqlFile);
    }
    $sql = "SELECT * FROM `{$table}` LIMIT 0,10";
    $query = $DB->query($sql);
    $query->setFetchMode(PDO::FETCH_ASSOC);
    $rt = $query->fetchAll();
    if ($rt) {
        $items = array();
        foreach ($rt as $item) {
            $tmp = array();
            $tmp['openid'] = $item['tb_item_id'];
            $tmp['iid'] = $item['tb_iid'];
            $tmp['price'] = $item['price'] ? $item['price'] / 100 : $item['reserve_price'] / 100;
            $tmp['name'] = $item['name'];
            $tmp['pic'] = $item['pic'];
            $tmp['itemType'] = $item['is_mall'] + 1;
            // 客户端判断是 1:集市店,2:天猫店
            $items[] = $tmp;
        }
        Ajax::go($items);
    } else {
        Ajax::error('数据查询失败.');
    }
}
开发者ID:yyueshui,项目名称:taobaokedemo,代码行数:33,代码来源:api.php

示例10: testLongWork

 public function testLongWork()
 {
     // work_test
     $pdo = new PDO_instance('sqlite::memory:', null, null, [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION]);
     $pdo->query('CREATE TABLE IF NOT EXISTS `work_test` (
         `key` varchar(128) DEFAULT NULL,
         `value` varchar(256) DEFAULT NULL
     );');
     $pdo->query(" DELETE FROM `work_test`;");
     // clear table data
     for ($i = 1; $i <= 100; $i++) {
         $pdo->query("INSERT INTO `work_test` (`key`, `value`) VALUES ('key" . $i . "', '" . mt_rand(0, 50) . "');");
     }
     $builder = new Builder($pdo);
     $this->assertInstanceOf('\\YepSQL\\Builder', $builder);
     #
     $this->assertEquals(3230, count($builder->loadFromFile(__DIR__ . '/true_long.sql')));
     $count = $pdo->query('SELECT count(*) FROM `work_test` WHERE `value` > 32;')->fetchColumn();
     $re = $builder->workLongMore([':more' => 32])->fetchColumn();
     print_r($re);
     $this->assertEquals($count, $re);
     #
     $count = $pdo->query('SELECT count(*) FROM `work_test` WHERE `value` < 32;')->fetchColumn();
     $re = $builder->workLongLess([':less' => 32])->fetchColumn();
     print_r($re);
     $this->assertEquals($count, $re);
     #
 }
开发者ID:LionsHead,项目名称:YepSQL,代码行数:28,代码来源:BuilderWorkTest.php

示例11: export

 public static function export(\PDO $database, $databaseName)
 {
     try {
         $stmt = $database->query('SHOW TABLES');
         $db = new Database($databaseName);
         foreach ($stmt as $k => $v) {
             $table = new Table();
             $table->setName($v[0]);
             $query = $database->query('SHOW COLUMNS FROM ' . $table->getName());
             $columns = $query->fetchAll(\PDO::FETCH_ASSOC);
             foreach ($columns as $c) {
                 $column = new Column();
                 $column->setName($c['Field']);
                 $column->setDefault($c['Default']);
                 $column->setExtra($c['Extra']);
                 $column->setKey($c['Key']);
                 $column->setNull($c['Null']);
                 $column->setType($c['Type']);
                 $table->addColumn($column);
             }
             $db->addTable($table);
         }
         $stmt->closeCursor();
     } catch (\PDOException $e) {
         echo "Error: " . $e->getMessage();
         exit;
     }
     return $db;
 }
开发者ID:TidioLtd,项目名称:DbDiff,代码行数:29,代码来源:Exporter.php

示例12: getConnection

 /**
  * Connects to the database without initializing contao
  *
  * @param OutputInterface $output = null
  *
  * @throws \Exception
  * @return \PDO
  */
 public function getConnection(OutputInterface $output = null)
 {
     if ($output == null) {
         $output = new NullOutput();
     }
     if ($this->_connection) {
         return $this->_connection;
     }
     $this->detectDbSettings($output);
     if (!extension_loaded('pdo_mysql')) {
         throw new \Exception('pdo_mysql extension is not installed');
     }
     if (strpos($this->dbSettings['host'], '/') !== false) {
         $this->dbSettings['unix_socket'] = $this->dbSettings['host'];
         unset($this->dbSettings['host']);
     } else {
         if (strpos($this->dbSettings['host'], ':') !== false) {
             list($this->dbSettings['host'], $this->dbSettings['port']) = explode(':', $this->dbSettings['host']);
         }
     }
     $this->_connection = new \PDO($this->dsn(), $this->dbSettings['username'], $this->dbSettings['password']);
     /** @link http://bugs.mysql.com/bug.php?id=18551 */
     $this->_connection->query("SET SQL_MODE=''");
     try {
         $this->_connection->query('USE `' . $this->dbSettings['dbname'] . '`');
     } catch (\PDOException $e) {
     }
     $this->_connection->query("SET NAMES utf8");
     $this->_connection->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true);
     $this->_connection->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
     return $this->_connection;
 }
开发者ID:iMi-digital,项目名称:imi-conrun,代码行数:40,代码来源:DatabaseHelper.php

示例13: executeSql

 /**
  * Execute une requête SQL (mysql).
  *
  * @todo implémenter le template.
  * @todo eviter de dupliquer les objets PDO, mais maintenir le renvoi d'une collection ouverte sur la BD
  * @param string $sql
  * @param string $template
  * @throws PDOException
  * @throws Afup_Directory_Exception
  * @return integer|PDOStatement insert or select
  */
 private function executeSql($sql, $template = null, $values = null)
 {
     if ($values) {
         $stmt = $this->pdo->prepare($sql);
         if ($stmt) {
             if (isset($values[0]) && is_array($values[0])) {
                 foreach ($values as $value) {
                     $stmt->execute($value);
                 }
             } else {
                 $stmt->execute($values);
             }
         }
     } else {
         $stmt = $this->pdo->query($sql, PDO::FETCH_ASSOC);
     }
     $queryType = strtolower(substr($sql, 0, 6));
     switch ($queryType) {
         case 'select':
             return $stmt;
             // break;
         // break;
         case 'insert':
         case 'update':
         case 'delete':
             unset($stmt);
             return $this->pdo->lastInsertId();
             // break;
         // break;
         default:
             throw new Afup_Directory_Exception("This request do not return values.");
             break;
     }
 }
开发者ID:fferriere,项目名称:web,代码行数:45,代码来源:Directory.php

示例14: tearDown

 /**
  * Drop test table, only on Travis CI
  */
 public function tearDown()
 {
     if (!$this->isTravisCi()) {
         return true;
     }
     $this->pdo->query("DROP TABLE hello");
 }
开发者ID:tomkyle,项目名称:databases,代码行数:10,代码来源:TestCaseBaseClass.php

示例15: like

function like($pid, $how)
{
    // database connection
    $dsn = "mysql:host=localhost;dbname=fundbook";
    //$options = array(PDO::"MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
    $db = new PDO($dsn, "root", "fundbook");
    $projects = $db->query("SELECT * FROM projects WHERE pid='{$pid}'");
    foreach ($projects as $project) {
        $author = $project["user"];
        $goal = $project["goal"];
        $category = $project["topic"];
        $title = $project["name"];
        $numBackers = $project["numBackers"];
        $raisedAmt = $project["raisedAmt"];
    }
    if (isset($_COOKIE["email"])) {
        $email = $_COOKIE["email"];
        $interested = $db->query("SELECT * FROM topicInterests WHERE person='{$email}' and topic='{$category}'");
        // then add to interest
        foreach ($interested as $interest) {
            if ($how == 'explicit') {
                $data = array('action' => 'like', "msg" => "added already");
                echo json_encode($data);
                exit;
            }
        }
        $db->query("INSERT INTO topicInterests VALUES ('{$email}', '{$category}')");
        if ($how == 'explicit') {
            $data = array('action' => 'like', 'msg' => 'added');
            echo json_encode($data);
        }
    }
    exit;
}
开发者ID:centaurustech,项目名称:fundbook,代码行数:34,代码来源:ajax_functions.php


注:本文中的PDO::query方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。