public static function getRow(\Pdo $pdo, array $columns, string $tableName, array $conditions) { $query = self::baseQuery($columns, $tableName); $query .= DefaultFunctions::addConditionsToQuery($conditions); $query .= ' LIMIT 1'; return self::executeFetchStatement($pdo->prepare($query)); }
function it_finds_multiple_records_by_name(\Pdo $connection, \PDOStatement $sqlResult) { $searchForName = "oso"; $expectedObject = array(new StringRecord(1, $searchForName), new StringRecord(1, $searchForName)); $connection->prepare("SELECT * FROM Testtable WHERE `name` = :name;")->willReturn($sqlResult); $sqlResult->execute(array('name' => $searchForName))->shouldBeCalled(); $sqlResult->fetchObject("\\spec\\MusicAnt\\DataSource\\StringRecord")->willReturn($expectedObject); $this->find(array('name' => $searchForName))->shouldReturn($expectedObject); }
public function setup() { $pdo = new \Pdo($GLOBALS['DB_DSN'], $GLOBALS['DB_USER'], $GLOBALS['DB_PASSWD'], array(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true, \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC)); $sql = "\n DROP TABLE IF EXISTS `entity`;\n CREATE TABLE `entity` (\n `id` int(11) unsigned NOT NULL AUTO_INCREMENT,\n `name` varchar(225) DEFAULT NULL,\n PRIMARY KEY (`id`)\n );\n "; $stmt = $pdo->prepare($sql); $stmt->execute(); require_once 'Mikron.php'; $this->mikron = new Mikron($pdo); }
function connect() { try { $connexion = new Pdo('mysql: host=' . HOST . ';dbname=' . DBNAME, USER, PW); $connexion->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $connexion; } catch (PDOexception $e) { echo "problème de connexion" . $e->getMessage(); return false; } }
protected function getPdoDriver() { $pdo = new PHPDataObject('sqlite::memory:'); $pdo->query("\n CREATE TABLE IF NOT EXISTS user(\n id_user INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n login VARCHAR(20) UNIQUE,\n name VARCHAR(50),\n email VARCHAR(50),\n password VARCHAR(50)\n );\n "); $data = [['duodraco', 'Anderson Casimiro', '*****@*****.**', '********'], ['fulano', 'Fulano de Tal', '*****@*****.**', 'f*******'], ['beltrano', 'Beltrano da Silva', '*****@*****.**', 'b*******'], ['beltrano2', 'Beltrano da Silva', '*****@*****.**', 'b*******'], ['gringo', 'John Doe', '*****@*****.**', 'j*******']]; foreach ($data as $each) { $pdo->query("\n INSERT INTO user (login, name, email, password)\n VALUES ('{$each[0]}','{$each[1]}','{$each[2]}','{$each[3]}');\n "); } $driver = new Pdo($pdo); return $driver; }
/** * @return TestDbAcle; */ public static function create(\Pdo $pdo, $factoryOverrides = array(), $factories = null) { if (is_null($factories)) { $factories = new Config\DefaultFactories(); } $testDbAcle = new TestDbAcle(); $serviceLocator = new ServiceLocator($factories->getFactories($pdo->getAttribute(\PDO::ATTR_DRIVER_NAME))); $serviceLocator->addFactories($factoryOverrides); $serviceLocator->setService('pdo', $pdo); $testDbAcle->setServiceLocator($serviceLocator); return $testDbAcle; }
/** * {@inheritdoc} */ public function restore($dumpTargetFile, array $ignoreTables = []) { $connection = new Pdo("mysql:host={$this->host};port=3306", $this->username, $this->password); $connection->query("USE {$this->database}"); foreach ($connection->query('SHOW TABLES')->fetchAll(PDO::FETCH_ASSOC) as $table) { $table = array_pop($table); if (in_array($table, $ignoreTables)) { continue; } $connection->query("DROP TABLE `{$table}`")->execute(); } $sql = file_get_contents($dumpTargetFile); $connection->prepare($sql)->execute(); }
/** * @see \PDOStatement::execute */ public function execute(array $input_parameters = array()) { $start = microtime(true); $result = $this->statement->execute($input_parameters); $this->pdo->addLog(array('query' => $this->statement->queryString, 'time' => microtime(true) - $start, 'values' => array_merge($this->binds, $input_parameters))); return $result; }
/** * @override */ public function prepare($statement, $options = array()) { $result = parent::prepare($statement, $options); if ($result instanceof \PDOStatement) { return new PdoStatement($this, $result); } return $result; }
/** * Prepares the PDO statements */ protected function prepareStatements() { if (!empty($this->statements)) { return; } $this->statements['load'] = $this->db->prepare('SELECT * FROM `' . $this->options['table'] . '` WHERE `userId` = :userId ' . 'AND `scope` = :scope AND `name` = :name AND `args` = :args'); $this->statements['save'] = $this->db->prepare('INSERT INTO `' . $this->options['table'] . '` (`userId`, `scope`, `name`, `args`, `cachedUntil`, `xml`) VALUES ' . '(:userId, :scope, :name, :args, :cachedUntil, :xml)'); $this->statements['delete'] = $this->db->prepare('DELETE FROM`' . $this->options['table'] . '` WHERE `userId` = :userId ' . 'AND `scope` = :scope AND `name` = :name AND `args` = :args'); }
/** * Destroys the database and user for the current application. * @return void */ private function destroyMySQL() { $this->appNameRequired(); if ($this->mysql->query('SHOW DATABASES LIKE \'db_' . $this->appname . '\';')->fetchObject()) { $this->writeln('Detected a Application MySQL user and database...'); $this->mysql->exec('DROP DATABASE IF EXISTS `db_' . $this->appname . '`;'); $this->mysql->exec('DROP USER \'' . $this->appname . '\'@\'' . $this->conf->mysql->confrom . '\';'); $this->mysql->exec('FLUSH PRIVILEGES;'); } }
static function transaction(callable $transaction) { self::$inst->beginTransaction(); $queue = $transaction(); if ($queue) { self::$inst->commit(); return $queue; } self::$inst->rollBack(); return false; }
/** * Gets number of rows returned by a resultset * <code> * $result = $connection->query("SELECT * FROM robots ORDER BY name"); * echo 'There are ', $result->numRows(), ' rows in the resultset'; * </code>. * * @return int */ public function numRows() { $rowCount = $this->_rowCount; if ($rowCount === false) { $rowCount = $this->_pdoStatement->rowCount(); if ($rowCount === false) { parent::numRows(); } $this->_rowCount = $rowCount; } return $rowCount; }
/** * Delete data * @param [id] [data's id] */ public function delete($id) { $sql = "DELETE FROM " . $this->table . " WHERE id = :id"; try { $delete = $this->conn->prepare($sql); $delete->bindValue(':id', $id, \PDO::PARAM_INT); if ($delete->execute()) { return true; } } catch (PDOexception $e) { return false; } }
/** * Get table checksum * @return mixed */ private function getTableChecksum() { $sql = "CHECKSUM TABLE items"; $q = $this->db->prepare($sql); $q->execute(); $rows = $q->fetchAll(); if (is_array($rows) && isset($rows[0]['Checksum'])) { $checksum = (int) $rows[0]['Checksum']; } else { $checksum = null; } return $checksum; }
/** * 执行sql语句 * @param string $sql sql语句 * @param array $params 参数 * @throws \PDOException */ public function query($sql, array $params = array()) { if (defined('DEBUG_SQL')) { // 输出调试的sql语句 echo "<pre>placeholder sql: {$sql}<hr/>"; print_r($params); foreach ($params as $key => $placeholder) { // 字符串加上引号 is_string($placeholder) and $placeholder = "'{$placeholder}'"; $start = strpos($sql, $key); $end = strlen($key); $sql = substr_replace($sql, $placeholder, $start, $end); } exit("<hr/> origin sql: {$sql}</pre>"); } // 预处理语句 $this->stmt = $this->pdo->prepare($sql); // 参数绑定 $this->bindValue($params); // sql语句执行 $this->stmt->execute(); // 结果解析成数组 $this->stmt->setFetchMode(\PDO::FETCH_ASSOC); }
/** * Modifie une ligne en fonction d'un identifiant * @param array $data Un tableau associatif de valeurs à insérer * @param mixed $id L'identifiant de$ la ligne à modifier * @param boolean $stripTags Active le strip_tags automatique sur toutes les valeurs * @return mixed La valeur de retour de la méthode execute() */ public function update(array $data, $id, $stripTags = true) { if (!is_numeric($id)) { return false; } $sql = "UPDATE " . $this->table . " SET "; foreach ($data as $key => $value) { $sql .= "{$key} = :{$key}, "; } $sql = substr($sql, 0, -2); $sql .= " WHERE id = :id"; $sth = $this->dbh->prepare($sql); foreach ($data as $key => $value) { $value = $stripTags ? strip_tags($value) : $value; $sth->bindValue(":" . $key, $value); } $sth->bindValue(":id", $id); return $sth->execute(); }
public function loadConnection() { if (!$this->_conn) { parent::loadConnection(); $this->_columns = \Gacela\Gacela::instance()->cacheMetaData($this->_config->schema . '_columns'); if (!$this->_columns) { $sql = "SELECT *\n\t\t\t\t\t\tFROM information_schema.COLUMNS\n\t\t\t\t\t\tWHERE TABLE_SCHEMA = DATABASE()"; $this->_columns = $this->query($sql)->fetchAll(\PDO::FETCH_OBJ); \Gacela\Gacela::instance()->cacheMetaData($this->_config->schema . '_columns', $this->_columns); } } // Moved out of __construct to allow for lazy loading of config data $this->_relationships = \Gacela\Gacela::instance()->cacheMetaData($this->_config->schema . '_relationships'); if (!$this->_relationships) { $fk = 'fk' . static::$_separator . '%' . static::$_separator . '%'; $sql = "\n\t\t\t\tSELECT\n\t\t\t\t\tTABLE_NAME AS keyTable,\n\t\t\t\t\tGROUP_CONCAT(COLUMN_NAME) AS keyColumns,\n\t\t\t\t\tREFERENCED_TABLE_NAME AS refTable,\n\t\t\t\t\tGROUP_CONCAT(REFERENCED_COLUMN_NAME) AS refColumns,\n\t\t\t\t\tCONSTRAINT_NAME AS constraintName\n\t\t\t\tFROM information_schema.key_column_usage\n\t\t\t\tWHERE TABLE_SCHEMA = DATABASE()\n\t\t\t\tAND CONSTRAINT_NAME LIKE '{$fk}'\n\t\t\t\tAND REFERENCED_TABLE_NAME IS NOT NULL\n\t\t\t\tGROUP BY constraintName\n\t\t\t\t"; $this->_relationships = $this->query($sql)->fetchAll(\PDO::FETCH_OBJ); \Gacela\Gacela::instance()->cacheMetaData($this->_config->schema . '_relationships', $this->_relationships); } }
protected function setPdoError() { $this->error_code = $this->pdo->errorCode(); $info = $this->pdo->errorInfo(); $this->error_info = implode(' ', $info); }
/** * Retourne l'identifiant de la dernière ligne insérée * @return int L'identifiant */ public function lastInsertId() { return $this->dbh->lastInsertId(); }
is_dir($v) ? del($v) : unlink($v); } return rmdir($dir); } del('upload'); echo 1; exit; } } //安装完成,添加数据 if ($action == 'table') { //添加数据表 $dsn = "mysql:host={$_SESSION['config']['host']};dbname={$_SESSION['config']['database']}"; $username = $_SESSION['config']['user']; $password = $_SESSION['config']['password']; $pdo = new Pdo($dsn, $username, $password, [PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'"]); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //执行建表语句 if (is_file('data/install.sql')) { $sql = file_get_contents('data/install.sql'); $sql = preg_replace('/^(\\/\\*|#.*).*/m', '', $sql); //替换表前缀 $sql = str_replace('`hd_', '`' . $_SESSION['config']['prefix'], $sql); $result = preg_split('/;(\\r|\\n)/is', $sql); foreach ((array) $result as $r) { if (preg_match('/^\\s*[a-z]/i', $r)) { try { $pdo->exec($r); } catch (PDOException $e) { die('SQL执于失败:' . $r . '. ' . $e->getMessage()); }
public function testCreatePdoStorageUsingConfig() { $config = array('dsn' => sprintf('sqlite://%s', Bootstrap::getInstance()->getSqliteDir())); $storage = new Pdo($config); $this->assertNotNull($storage->getClientDetails('oauth_test_client')); }
/** * Clear data from the query or a specific clause of the query. * * @param string $clause Optionally, the name of the clause to clear, or nothing to clear the whole query. * * @return JDatabaseQuery Returns this object to allow chaining. * * @since 12.1 */ public function clear($clause = null) { switch ($clause) { case null: $this->bounded = array(); break; } parent::clear($clause); return $this; }
public function __construct() { parent::__construct('sqlite::memory:'); }
<?php $db = new Pdo(''); $buys = array(); $buycds = array(); $ids = array(); $sth = $db->prepare('select * from buy'); $sth->execute(array()); while ($line = $sth->fetch()) { $line['buy_items'] = array(); $buys[$line['buycd']] = $line; $buycds[$line['buycd']] = $line['buycd']; $ids[$line['id']] = $line['id']; } $sth->closeCursor(); $itemcds = array(); if (count($buycds)) { $sth = $db->prepare('select * from buy_item where buycd in (' . implode(',', $buycds) . ')'); $sth->execute(array()); while ($line = $sth->fetch()) { $buys[$line['buycd']]['buy_items'][$line['seq']] = $line; $itemcds[$line['itemcd']] = $line['itemcd']; } $sth->closeCursor(); } $items = array(); if (count($itemcds)) { $sth = $db->prepare('select * from item where itemcd in (' . implode(',', $itemcds) . ')'); $sth->execute(array()); while ($line = $sth->fetch()) { $items[$line['itemcd']] = $line;
/** * Method to initialize a transaction. * * @param boolean $asSavepoint If true and a transaction is already active, a savepoint will be created. * * @return void * * @since 12.3 * @throws RuntimeException */ public function transactionStart($asSavepoint = false) { $this->connect(); if (!$asSavepoint || !$this->transactionDepth) { return parent::transactionStart($asSavepoint); } $savepoint = 'SP_' . $this->transactionDepth; $this->setQuery('SAVEPOINT ' . $this->quoteName($savepoint)); if ($this->execute()) { $this->transactionDepth++; } }
public function runPdoSql(\PDO $pdo) { $storage = new Pdo($pdo); foreach (explode(';', $storage->getBuildSql()) as $statement) { $result = $pdo->exec($statement); } // set up scopes $sql = 'INSERT INTO oauth_scopes (scope) VALUES (?)'; foreach (explode(' ', 'supportedscope1 supportedscope2 supportedscope3 supportedscope4 clientscope1 clientscope2 clientscope3') as $supportedScope) { $pdo->prepare($sql)->execute(array($supportedScope)); } $sql = 'INSERT INTO oauth_scopes (scope, is_default) VALUES (?, ?)'; foreach (array('defaultscope1', 'defaultscope2') as $defaultScope) { $pdo->prepare($sql)->execute(array($defaultScope, true)); } // set up clients $sql = 'INSERT INTO oauth_clients (client_id, client_secret, scope, grant_types) VALUES (?, ?, ?, ?)'; $pdo->prepare($sql)->execute(array('Test Client ID', 'TestSecret', 'clientscope1 clientscope2', null)); $pdo->prepare($sql)->execute(array('Test Client ID 2', 'TestSecret', 'clientscope1 clientscope2 clientscope3', null)); $pdo->prepare($sql)->execute(array('Test Default Scope Client ID', 'TestSecret', 'clientscope1 clientscope2', null)); $pdo->prepare($sql)->execute(array('oauth_test_client', 'testpass', null, 'implicit password')); // set up misc $sql = 'INSERT INTO oauth_access_tokens (access_token, client_id, expires, user_id) VALUES (?, ?, ?, ?)'; $pdo->prepare($sql)->execute(array('testtoken', 'Some Client', date('Y-m-d H:i:s', strtotime('+1 hour')), null)); $pdo->prepare($sql)->execute(array('accesstoken-openid-connect', 'Some Client', date('Y-m-d H:i:s', strtotime('+1 hour')), 'testuser')); $sql = 'INSERT INTO oauth_authorization_codes (authorization_code, client_id, expires) VALUES (?, ?, ?)'; $pdo->prepare($sql)->execute(array('testcode', 'Some Client', date('Y-m-d H:i:s', strtotime('+1 hour')))); $sql = 'INSERT INTO oauth_users (username, password, email, email_verified) VALUES (?, ?, ?, ?)'; $pdo->prepare($sql)->execute(array('testuser', 'password', '*****@*****.**', true)); $sql = 'INSERT INTO oauth_public_keys (client_id, public_key, private_key, encryption_algorithm) VALUES (?, ?, ?, ?)'; $pdo->prepare($sql)->execute(array('ClientID_One', 'client_1_public', 'client_1_private', 'RS256')); $pdo->prepare($sql)->execute(array('ClientID_Two', 'client_2_public', 'client_2_private', 'RS256')); $sql = 'INSERT INTO oauth_public_keys (client_id, public_key, private_key, encryption_algorithm) VALUES (?, ?, ?, ?)'; $pdo->prepare($sql)->execute(array(null, $this->getTestPublicKey(), $this->getTestPrivateKey(), 'RS256')); $sql = 'INSERT INTO oauth_jwt (client_id, subject, public_key) VALUES (?, ?, ?)'; $pdo->prepare($sql)->execute(array('oauth_test_client', 'test_subject', $this->getTestPublicKey())); }
public static function tearDownAfterClass() { $sth = self::$pdo->prepare("DROP TABLE IF EXISTS users"); $sth->execute(); }
*/ $conferenceId = 3664; /** * Default speaker URI * * Change this value to specify a different default speaker URI when a speaker does not have an entry on joind.in. */ $defaultSpeakerUri = 'http://www.zendcon.com'; /** * Default speaker twitter username * * Change this value to specify a different default speaker twitter username when a speaker does not have an entry on joind.in. */ $defaultSpeakerTwitter = 'zendcon'; $dbPath = realpath(__DIR__ . '/../data/db/conference.db'); $pdo = new Pdo('sqlite:' . $dbPath); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $insertSpeaker = $pdo->prepare('INSERT INTO speakers (id, name, url, twitter) VALUES (:id, :name, :url, :twitter)'); $insertTalk = $pdo->prepare('INSERT INTO talks (id, title, abstract, day, start_time) VALUES (:id, :title, :abstract, :day, :start_time)'); $insertLink = $pdo->prepare('INSERT INTO talks_speakers (talk_id, speaker_id) VALUES (:talk_id, :speaker_id)'); $client = new Client(); $client->setOptions(['adapter' => Curl::class]); $request = $client->getRequest(); $headers = $request->getHeaders(); $headers->addHeaderLine('Accept', 'application/json'); $client->setUri(sprintf('http://api.joind.in/v2.1/events/%d/talks?verbose=yes&resultsperpage=0', $conferenceId)); $client->setMethod('GET'); printf("Fetching talks for ZendCon 2015..."); $response = $client->send(); $json = $response->getBody(); $payload = json_decode($json);
<?php require_once __DIR__ . '/../vendor/autoload.php'; require_once __DIR__ . '/../lib/highlight.php'; /** * We don't need no stinking architecture!1!! * * Seriously though, Silex was an obvious choice as the website is quite simple * at the moment. We might want to migrate to something else when the website gets * bigger, but for now, this works like a charm! */ $config = (require __DIR__ . '/../config.php'); $db = new Pdo($config['database']['dsn'], $config['database']['username'], $config['database']['password']); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); /** * Gets the recent pastes from the database. * * @param PDO $db * @return array */ $getRecent = function ($db) { $stmt = $db->query('SELECT paste_id, name, added FROM paste ORDER BY added DESC LIMIT 5 OFFSET 0'); $stmt->execute(); $recent = $stmt->fetchAll(); return $recent !== false ? $recent : array(); }; /** * Gets the details of a paste from the database. * * @param PDO $db