/** * Prepare and execute a query. * * If the query fails, output a diagnostic message * @param string $query * Query to run * @return bool */ public function do_query($query) { // echo "do_query($query)\n"; // $stmt = $this->pdo->query( $query, PDO::FETCH_ASSOC ); // echo "PDO returned"; // var_dump($stmt); $string = preg_replace("/^#[^\n]*\$/m", "\n", $query); $string = preg_replace("/^(--[^-]).*/m", "\n", $string); $queries = preg_split('/;\\s*$/m', $string); foreach ($queries as $query) { $query = trim($query); if (!empty($query)) { $result = $this->pdo->query($query); if ($this->pdo->errorCode() == 0) { continue; } else { var_dump($result); var_dump($this->pdo->errorInfo()); // die( "Cannot execute $query: " . $this->pdo->errorInfo() ); } } } /******* * if ( $this->pdo->errorCode() == 0 ) { * //echo "returning the PDOStmt\n"; * return $stmt; * } * * // operation failed, so output description of where and why * $errorInfo = $this->pdo->errorInfo(); * echo "Oops, can't do query:\n {$query}\n in " * . basename( __FILE__) . " line " . __LINE__.":\n " * . $errorInfo[0] . ": " . $errorInfo[2] . "\n Call stack:\n"; * $backtrace = debug_backtrace(); * $dir_name = dirname( __FILE__ ); * $cwd_len = strlen( $dir_name ) + 1; * foreach ($backtrace as $frame ) { * echo " "; * if ( array_key_exists( 'class', $frame ) ) { * echo " class {$frame['class']}"; * if ( array_key_exists( 'function', $frame ) ) { * echo " method {$frame['function']}"; * } * } * else { * if ( array_key_exists( 'function', $frame ) ) { * echo " function {$frame['function']}"; * } * } * if ( array_key_exists( 'file', $frame ) ) { * echo " file ". substr( $frame['file'], $cwd_len ); * } * if ( array_key_exists( 'line', $frame ) ) { * echo " line {$frame['line']}"; * } * echo "\n"; * } ******/ return TRUE; }
/** * Tests MySQL connection * * @return void */ public function testMySQL() { try { $pdo = new PDO( "mysql:host=" . TESTSUITE_SERVER . ";dbname=" . TESTSUITE_DATABASE, TESTSUITE_USER, TESTSUITE_PASSWORD ); $this->assertNull( $pdo->errorCode(), "Error when trying to connect to database" ); //$pdo->beginTransaction(); $test = $pdo->exec("SHOW TABLES;"); //$pdo->commit(); $this->assertEquals( 0, $pdo->errorCode(), 'Error trying to show tables for database' ); } catch (Exception $e) { $this->fail("Error: ".$e->getMessage()); } // Check id MySQL server is 5 version preg_match( "/^(\d+)?\.(\d+)?\.(\*|\d+)/", $pdo->getAttribute(constant("PDO::ATTR_SERVER_VERSION")), $version_parts ); $this->assertEquals(5, $version_parts[1]); }
public function __construct(PDO $dbh) { if ($dbh->errorCode() !== NULL) { echo "database handle invalid, error code " . $dbh->errorCode(); return; } $this->dbh = $dbh; }
/** * @return Member[] */ public function getMembers() { $statement = $this->pdo->query('SELECT * FROM members'); if (false === $statement) { throw new \PDOException(join("\n", $this->pdo->errorInfo()), $this->pdo->errorCode()); } $members = []; while ($row = $statement->fetch(\PDO::FETCH_OBJ)) { $members[] = $this->rowToMember($row); } return $members; }
public function checkDatabase() { try { $this->pdo->query("select 1 from `{$this->tableName}` limit 1"); if ($this->pdo->errorCode() == '00000') { return; } //return; } catch (\Exception $ex) { } $this->pdo->exec("DROP TABLE IF EXISTS `{$this->tableName}`"); $this->pdo->exec("\nCREATE TABLE IF NOT EXISTS `{$this->tableName}` (\n `shopname` varchar(255) DEFAULT NULL,\n `scope` varchar(255) DEFAULT NULL,\n `nonce` varchar(255) DEFAULT NULL,\n `token` varchar(255) DEFAULT NULL,\n `last_modified` timestamp NULL DEFAULT CURRENT_TIMESTAMP,\n PRIMARY KEY (`shopname`,`scope`)\n)"); }
/** * Tests MySQL connection * * @return void */ public function testMySQL() { try { $pdo = new PDO("mysql:host=" . $GLOBALS['TESTSUITE_SERVER'], $GLOBALS['TESTSUITE_USER'], $GLOBALS['TESTSUITE_PASSWORD']); $this->assertNull($pdo->errorCode(), "Error when trying to connect to database"); $pdo->exec("SHOW DATABASES;"); $this->assertEquals(0, $pdo->errorCode(), 'Error trying to show tables for database'); } catch (Exception $e) { $this->markTestSkipped("Error: " . $e->getMessage()); } // Check id MySQL server is 5 version preg_match("/^(\\d+)?\\.(\\d+)?\\.(\\*|\\d+)/", $pdo->getAttribute(constant("PDO::ATTR_SERVER_VERSION")), $version_parts); $this->assertEquals(5, $version_parts[1]); }
/** * Internal function to execute PDO queries when the * query option is set to a PDO object * @param string $query The SQL query to execute * @param array $parameters Parameters to bind to the query * @return array */ function executePdoQuery($query, $parameters) { $stmt = $this->dbh->prepare($query); if (!$stmt) { echo "Error in preparing query: " . $this->dbh->errorCode() . " " . htmlentities(print_r($this->dbh->errorInfo(), true)) . " " . htmlentities($query); exit; } $res = $stmt->execute($parameters); if (!$res) { echo "Error in executing query: " . $stmt->errorCode() . " " . htmlentities(print_r($stmt->errorInfo(), true)) . " " . htmlentities($query); exit; } return $stmt->fetchAll(\PDO::FETCH_ASSOC); }
public function errorCode() { if ($this->connected) { return parent::errorCode(); } return 0; }
/** * Returns the number of the last error. * * @return integer */ public function getErrorNumber() { if ($this->pdo !== null) { return $this->pdo->errorCode(); } return 0; }
/** * Executes a SQL statement * * @param mixed $po_caller object representation of the calling class, usually Db() * @param PDOStatement $opo_statement * @param string $ps_sql SQL statement * @param array $pa_values array of placeholder replacements * @return bool|DbResult */ public function execute($po_caller, $opo_statement, $ps_sql, $pa_values) { if (!$ps_sql) { $po_caller->postError(240, _t("Query is empty"), "Db->pdo_mysql->execute()"); return false; } if (!$opo_statement instanceof PDOStatement) { $po_caller->postError(250, _t("Invalid prepared statement"), "Db->pdo_mysql->execute()"); return false; } if (!is_array($va_tmp = self::rewriteQueryAndParams($ps_sql, $pa_values))) { $po_caller->postError(250, _t("Query rewrite failed"), "Db->pdo_mysql->execute()"); return false; } if ($va_tmp['prepare']) { $opo_statement = $this->opr_db->prepare($va_tmp['sql']); } if (Db::$monitor) { $t = new Timer(); } try { $opo_statement->closeCursor(); $opo_statement->execute(is_array($va_tmp['values']) && sizeof($va_tmp['values']) ? array_values($va_tmp['values']) : null); } catch (PDOException $e) { $po_caller->postError($po_caller->nativeToDbError($this->opr_db->errorCode()), $e->getMessage() . (__CA_ENABLE_DEBUG_OUTPUT__ ? "\n<pre>" . caPrintStacktrace() . "\n{$ps_sql}</pre>" : ""), "Db->pdo_mysql->execute()"); return false; } if (Db::$monitor) { Db::$monitor->logQuery($ps_sql, $pa_values, $t->getTime(4), $opo_statement->rowCount()); } return new DbResult($this, $opo_statement); }
/** * Check if server is still connected * @return bool */ public function is_connected() { if (!$this->dbh || 2006 == $this->dbh->errorCode()) { return false; } return true; }
public function errorCode() { if ($this->pdo == null) { return null; } return $this->pdo->errorCode(); }
/** * 数据库查询方法 * sql sql语句 * ret_type 返回类型,result/row/rows/value **/ function db_query(PDO $db, $sql, $ret_type = 'result') { /*$s = db_parsesql($sql); if(!$s){ return false; } */ if ($ret_type == 'result') { $result = $db->exec($sql); } else { $result = $db->query($sql); } if (!$result && $db->errorCode() != '00000') { //trigger_error('在MYSQL服务器端执行SQL语句失败.<br />SQL: ' . $sql . '<br />原因: '. $db->errorCode() . '<br />'); return false; } switch ($ret_type) { case "result": return $result; case "row": if ($result) { return $result->fetch(); } return false; case "rows": if ($result) { return $result->fetchAll(PDO::FETCH_ASSOC); } return false; default: trigger_error(__FUNCTION__ . " unknowd query type"); return false; } }
public function testPDOConnectionError() { $string_dsn = 'mysql:host= nosuchhost;dbname=nosuchdb'; $mypdo = new PDO($string_dsn, "nonesuchuser", "nonesuchpass"); // Should be an error set since we gave bogus info $this->assertTrue(strlen($mypdo->errorCode()) > 0, "Error code not being set on PDO object"); }
/** * @return Meetup[] */ public function getMeetups() { $statement = $this->pdo->query('SELECT m.*, count(r.member_identifier) as taken FROM meetups m LEFT JOIN rsvps r ON (r.meetup_identifier = m.identifier AND r.rsvp = "yes") GROUP BY m.identifier ORDER BY m.date ASC'); if (false === $statement) { throw new \PDOException(join("\n", $this->pdo->errorInfo()), $this->pdo->errorCode()); } $meetups = []; while ($row = $statement->fetch(\PDO::FETCH_OBJ)) { $meetups[] = $this->rowToMeetup($row); } return $meetups; }
public function exec($statement) { if (isset($this->dsn) and stristr($this->dsn, 'anjuke_db') and preg_match('/\\sajk_propertys\\s/i', $statement)) { if (stristr($statement, 'select CITYID') or stristr($statement, 'insert') or stristr($statement, 'update ')) { } else { $dir = '/home/www/logs/propsql'; if (!is_dir($dir)) { mkdir($dir, 0755, true); $content = '-=-=-=-=-=-=-=-=-=-=' . PHP_EOL; $content .= 'DSN: ' . $this->dsn . PHP_EOL; $content .= 'URI: ' . $_SERVER['REQUEST_URI'] . PHP_EOL; $content .= 'JOB: ' . var_export($_SERVER['argv'], true) . PHP_EOL; $content .= 'SQL: ' . $statement . PHP_EOL; file_put_contents($dir . '/' . date('Ymd'), $content, FILE_APPEND); } } } if (APF::get_instance()->is_debug_enabled()) { APF::get_instance()->debug(__CLASS__ . '[' . $this->name . ']' . "->exec: {$statement}"); } $logger = APF::get_instance()->get_logger(); $logger->debug(__CLASS__, '[' . $this->name . ']->exec: ', $statement); $stmt = parent::exec($statement); if ($stmt instanceof PDOStatement) { $stmt->setFetchMode($this->default_fetch_mode); } else { $error_info = parent::errorInfo(); if (parent::errorCode() !== '00000') { throw new APF_Exception_SqlException(parent::errorCode(), $this->get_name() . ' | ' . $this->config['dsn'] . ' | ' . $statement . ' | ' . join(' | ', $error_info)); } } return $stmt; }
public function __construct($message, PDO $pdo) { $infos = array(); foreach ($pdo->errorInfo() as $key => $info) { $infos[] = $key . ': ' . $info; } parent::__construct($message . '. (ERRNO ' . $pdo->errorCode() . ') ' . implode('<br />', $infos)); }
/** * Returns the last error code generated by the wrapped PDO object. Please * the PDOStatement::errorCode method for prepared statements. * * @access public * @author Jerome Bogaerts, <*****@*****.**> * @return string */ private function errorCode() { if ($this->preparedExec == false) { $returnValue = $this->dbConnector->errorCode(); } else { $returnValue = $this->lastPreparedExecStatement->errorCode(); } return (string) $returnValue; }
/** * This function checks if the last PDO operation on the database was successful. If not, the error will be reported to the Database error log. * * @param $pdo: The PDO Database connection * * @return boolean: True if the last operation was successful, false otherwise. */ public static function dbAssert(PDO $pdo) { if ($pdo->errorCode() != 0) { $info = $pdo->errorInfo(); self::log("Database Error " . $info[0] . " (" . $info[1] . " [driver-spec]): " . $info[2], 'error', "db"); return false; } return true; }
public function existe_socio($Socio) { $conn = new PDO($this->db['dsn'], $this->db['username'], $this->db['password']); if (!is_null($conn->errorCode())) { $this->msg = 'no conn'; } $consulta = $conn->prepare('SELECT "socio_url" FROM user WHERE socio_url = ? AND es_socio = 2', [PDO::ATTR_PERSISTENT => FALSE]); $consulta->execute([$Socio]); return $consulta->rowCount(); }
function error_check(PDO $pdo) { if ($pdo->errorCode() !== "00000") { global $v; echo "ERROR:"; echo implode(",", $pdo->errorInfo()); echo "\n-----------------SQL----------------\n"; echo $v; exit; } }
function insert_blob($server_cfg, $game_cfg, $tbz_file, $timestamp) { //$table = $game_cfg["xhprof_blob_daily_table"]; // Hardcoded $table = "xhprof_blob_daily"; $db_server = $game_cfg["db_host"]; $db_user = $game_cfg["db_user"]; $db_pass = $game_cfg["db_pass"]; $db_name = $game_cfg["db_name"]; $mysql_pdo = new PDO("mysql:host={$db_server};dbname={$db_name}", $db_user, $db_pass); if (!$mysql_pdo) { $game_cfg['logger']->log("Daily aggregation insert_tbz", "Failed to create PDO object", Logger::ERR); error_log("Daily aggregation Failed to create new mysql PDO\n", 3, $game_cfg['log_file']); return 1; } $tbz_handle = fopen($tbz_file, "rb"); if (!$tbz_handle) { $game_cfg['logger']->log("Daily aggregation insert_tbz", "Failed to open tbz file {${$tbz_file}}", Logger::INFO); error_log("Daily aggregation Failed to open tbz file {$tbz_file}.\n", 3, $game_cfg['log_file']); return 1; } $stmt = "REPLACE INTO {$table} (timestamp, xhprof_blob) VALUES (from_unixtime({$timestamp}), :tbz_handle)"; error_log("{$stmt}\n", 3, sprintf($server_cfg['log_file'], $game_cfg['name'])); $insert_statement = $mysql_pdo->prepare($stmt); if (!$insert_statement) { error_log("Daily aggregation Failed to create insert statement\n", 3, $game_cfg['log_file']); $game_cfg['logger']->log("Daily aggregation Insert_tbz", "Failed to create insert statement", Logger::ERR); error_log(print_r($mysql_pdo->errorCode(), true), 3, $game_cfg['log_file']); error_log(print_r($mysql_pdo->errorInfo(), true), 3, $game_cfg['log_file']); return 2; } if (!$insert_statement->bindParam(':tbz_handle', $tbz_handle, PDO::PARAM_LOB) || !$mysql_pdo->beginTransaction() || !$insert_statement->execute() || !$mysql_pdo->commit()) { error_log("Daily aggregation Failed to insert blob from file handle into db\n", 3, $game_cfg['log_file']); error_log(print_r($mysql_pdo->errorCode(), true), 3, $game_cfg['log_file']); error_log(print_r($mysql_pdo->errorInfo(), true), 3, $game_cfg['log_file']); $game_cfg['logger']->log("Daily aggregation Insert_tbz", "Failed to insert blob from file handle into db", Logger::ERR); return 3; } $game_cfg['logger']->log("Daily aggregation Insert_tbz", "{$tbz_file} : blob is inserted", Logger::INFO); return 0; }
public function getConnection($db_config) { $str = 'mysql:host=' . $db_config['host'] . ';port=' . $db_config['port'] . ';dbname=' . $db_config['db_name']; $connection = new PDO($str, $db_config['username'], $db_config['password']); try { $connection->exec('SET NAMES \'' . $db_config['encoding'] . '\';'); return $connection; } catch (PDOException $e) { throw new Exception($connection->errorCode()); //todo 出错时未定义变量 } }
protected function getCdr(PDO $db) { $min_date = date("1/m/Y"); $stsmt = $db->query("\n\t\t\tSELECT\n\t\t\t\tLOGID AS ID, LOGDATETIME AS DT, DURATION AS DUR, CALLCOST AS COST, NUMBERDIALED AS NUM\n\t\t\tFROM LOG WHERE PIN IN('2577') AND LOGDATETIME > #{$min_date}# ORDER BY LOGID DESC\n\t\t"); if ((int) $db->errorCode()) { $this->view->log = "There was error with error code: " . print_r($db->errorInfo(), true); $this->view->calls = array(); } else { $rs = $stsmt->fetchAll(PDO::FETCH_OBJ); $this->view->calls = $rs; } }
/** * Prepare and execute a query * * If the query fails, output a diagnostic message * @param string Query to run * @return mixed PDOStatement => Results of the query * false => Query failed */ function do_query($query) { //echo "do_query($query)\n"; $stmt = $this->pdo->query($query, PDO::FETCH_ASSOC); //echo "PDO returned"; //var_dump($stmt); if ($this->pdo->errorCode() == 0) { //echo "returning the PDOStmt\n"; return $stmt; } // operation failed, so output description of where and why $errorInfo = $this->pdo->errorInfo(); echo "Oops, can't do query:\n {$query}\n in " . basename(__FILE__) . " line " . __LINE__ . ":\n " . $errorInfo[0] . ": " . $errorInfo[2] . "\n Call stack:\n"; $backtrace = debug_backtrace(); $dir_name = dirname(__FILE__); $cwd_len = strlen($dir_name) + 1; foreach ($backtrace as $frame) { echo " "; if (array_key_exists('class', $frame)) { echo " class {$frame['class']}"; if (array_key_exists('function', $frame)) { echo " method {$frame['function']}"; } } else { if (array_key_exists('function', $frame)) { echo " function {$frame['function']}"; } } if (array_key_exists('file', $frame)) { echo " file " . substr($frame['file'], $cwd_len); } if (array_key_exists('line', $frame)) { echo " line {$frame['line']}"; } echo "\n"; } return false; }
function OpenDB() { global $sqlhost; global $sqldb; global $sqluser; global $sqlpasswd; global $mysqliDB; $mysqliDB = new PDO('mysql:host=' . $sqlhost . '; dbname=' . $sqldb . '; charset=utf8', $sqluser, $sqlpasswd); if (!$mysqliDB) { echo "Unable to connect to DB: (" . $mysqliDB->errorCode() . ") "; die; } return 0; }
/** * @param InputInterface $input Input from the user. * @param OutputInterface $output Output to the user. * @return bool Success. */ protected function ping(InputInterface $input, OutputInterface $output) { if ($this->connected === false) { $ret = $this->connect($input, $output); if ($ret === false) { return false; } } $errorLevel = error_reporting(); error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING); $this->startTime = microtime(true); try { $this->checkStmt = $this->dbh->query($this->checkSql); $this->stopTime = microtime(true); } catch (\PDOException $e) { $this->stopTime = microtime(true); error_reporting($errorLevel); $errorInfo = $this->dbh->errorInfo(); // server has gone away if (isset($errorInfo[1]) === true && $errorInfo[1] === 2006) { $this->connected = false; $this->writeReply('connection lost.', $input, $output); } else { $this->writeReply('check failed with exception: ' . rtrim($e->getMessage(), PHP_EOL . '.') . '.', $input, $output); } return false; } //end try error_reporting($errorLevel); if ($this->checkStmt === false) { $errorInfo = $this->dbh->errorInfo(); // server has gone away if (isset($errorInfo[1]) === true && $errorInfo[1] === 2006) { $this->connected = false; $this->writeReply('connection lost.', $input, $output); } else { $this->writeReply('check failed statement: [' . $this->dbh->errorCode() . '] ' . rtrim(implode(' ', $errorInfo), PHP_EOL . '.') . '.', $input, $output); } return false; } $ret = $this->queryCheck($input, $output); if ($ret === false) { return false; } return true; }
public function exec($statement) { if (APF::get_instance()->is_debug_enabled()) { APF::get_instance()->debug(__CLASS__ . '[' . $this->name . ']' . "->exec: {$statement}"); } $logger = APF::get_instance()->get_logger(); $logger->debug(__CLASS__, '[' . $this->name . ']->exec: ', $statement); $stmt = parent::exec($statement); if ($stmt instanceof PDOStatement) { $stmt->setFetchMode($this->default_fetch_mode); } else { $error_info = parent::errorInfo(); if (parent::errorCode() !== '00000') { throw new APF_Exception_SqlException($this->get_name() . ' | ' . $this->config['dsn'] . ' | ' . $statement . ' | ' . join(' | ', $error_info), parent::errorCode()); } } return $stmt; }
public function exec($statement) { if (APF::get_instance()->is_debug_enabled()) { APF::get_instance()->debug(__CLASS__ . '[' . $this->name . ']' . "->exec: {$statement}"); } $logger = APF::get_instance()->get_logger(); $logger->debug(__CLASS__, '[' . $this->name . ']->exec: ', $statement); $stmt = parent::exec($statement); if ($stmt instanceof PDOStatement) { $stmt->setFetchMode($this->default_fetch_mode); } else { $error_info = parent::errorInfo(); if (parent::errorCode() !== '00000') { trigger_error($statement . ' | ' . join(' | ', $error_info), E_USER_ERROR); } } return $stmt; }
/** * run any query * @param $query_string * @return bool|\PDOStatement * @throws \ErrorException */ public function doQuery($query_string) { $this->query = str_replace('{..pref..}', $this->pref, $query_string); // replace {..pref..} $this->result = $this->sql->query($this->query); // execute query if ($this->result !== false) { unset($this->error); return $this->result; } else { $this->error[0] = $this->sql->errorCode(); // error number $this->error[1] = $this->sql->errorInfo(); // error text $this->error[2] = $this->query; // query causing the error throw new \ErrorException('SQL Error: [' . $this->error[0] . '] ' . $this->error[1] . "\n" . $this->error[2]); } }