public static function castResult($result, array $a, Stub $stub, $isNested) { $a['num rows'] = pg_num_rows($result); $a['status'] = pg_result_status($result); if (isset(self::$resultStatus[$a['status']])) { $a['status'] = new ConstStub(self::$resultStatus[$a['status']], $a['status']); } $a['command-completion tag'] = pg_result_status($result, PGSQL_STATUS_STRING); if (-1 === $a['num rows']) { foreach (self::$diagCodes as $k => $v) { $a['error'][$k] = pg_result_error_field($result, $v); } } $a['affected rows'] = pg_affected_rows($result); $a['last OID'] = pg_last_oid($result); $fields = pg_num_fields($result); for ($i = 0; $i < $fields; ++$i) { $field = array('name' => pg_field_name($result, $i), 'table' => sprintf('%s (OID: %s)', pg_field_table($result, $i), pg_field_table($result, $i, true)), 'type' => sprintf('%s (OID: %s)', pg_field_type($result, $i), pg_field_type_oid($result, $i)), 'nullable' => (bool) pg_field_is_null($result, $i), 'storage' => pg_field_size($result, $i) . ' bytes', 'display' => pg_field_prtlen($result, $i) . ' chars'); if (' (OID: )' === $field['table']) { $field['table'] = null; } if ('-1 bytes' === $field['storage']) { $field['storage'] = 'variable size'; } elseif ('1 bytes' === $field['storage']) { $field['storage'] = '1 byte'; } if ('1 chars' === $field['display']) { $field['display'] = '1 char'; } $a['fields'][] = new EnumStub($field); } return $a; }
/** * 执行数据库查询 * * @param string $query 数据库查询SQL字符串 * @param mixed $handle 连接对象 * @param integer $op 数据库读写状态 * @param string $action 数据库动作 * @throws Typecho_Db_Exception * @return resource */ public function query($query, $handle, $op = Typecho_Db::READ, $action = NULL) { $isQueryObject = $query instanceof Typecho_Db_Query; $this->_lastTable = $isQueryObject ? $query->getAttribute('table') : NULL; if ($resource = @pg_query($handle, $isQueryObject ? $query->__toString() : $query)) { return $resource; } /** 数据库异常 */ throw new Typecho_Db_Query_Exception(@pg_last_error($this->_dbLink), pg_result_error_field(pg_get_result($this->_dbLink), PGSQL_DIAG_SQLSTATE)); }
public function rawQuery($sql, array $params = []) { if (empty($params)) { pg_send_query($this->dbconn, $sql); } else { pg_send_query_params($this->dbconn, $sql, $params); } $result = pg_get_result($this->dbconn); $err = pg_result_error($result); if ($err) { throw new \Pg\Exception($err, 0, null, pg_result_error_field($result, PGSQL_DIAG_SQLSTATE)); } return new \Pg\Statement($result, $this->typeConverter); }
public static function query($query) { try { $result = \pg_query(self::instance(), $query); if (!$result) { print_r(debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1)); } } catch (\Exception $e) { throw new \Exception("not executed: " . $query); } $error = \pg_result_error_field($result, PGSQL_DIAG_SQLSTATE); if ($error) { throw new \Exception($error); } return new Result($result); }
public function query($query) { if (!pg_send_query($this->connection, $query)) { throw $this->createException(pg_last_error($this->connection), 0, NULL); } $time = microtime(TRUE); $resource = pg_get_result($this->connection); $time = microtime(TRUE) - $time; if ($resource === FALSE) { throw $this->createException(pg_last_error($this->connection), 0, NULL); } $state = pg_result_error_field($resource, PGSQL_DIAG_SQLSTATE); if ($state !== NULL) { throw $this->createException(pg_result_error($resource), 0, $state, $query); } $this->affectedRows = pg_affected_rows($resource); return new Result(new PgsqlResultAdapter($resource), $this, $time); }
function ejecutarValidandoUniqueANDPrimaryKey($sql) { if ($sql == "") { return 0; } else { /* Si puede enviar la consulta sin importar que encuentre llaves duplicadas */ if (pg_send_query($this->connect, $sql)) { /* Ejecuta la consulta */ $this->consulta_ID = pg_get_result($this->connect); /* Se tiene algun resultado sin importar que contenga errores de duplidados */ if ($this->consulta_ID) { /* Detecte un posible error */ $state = pg_result_error_field($this->consulta_ID, PGSQL_DIAG_SQLSTATE); /* Si no se genero ningun error */ if ($state == 0) { return $this->consulta_ID; } else { /* Si encontro algun error */ return false; } } } } }
/** * Return an error number. * * @param resource $query * @return int The error number of the current error. */ function error_number($query = null) { if ($query != null || !function_exists("pg_result_error_field")) { return 0; } return pg_result_error_field($query, PGSQL_DIAG_SQLSTATE); }
function wpsql_errno($connection) { // throw new Exception("Error Processing Request", 1); if ($connection == 1) { return false; } $result = pg_get_result($connection); $result_status = pg_result_status($result); return pg_result_error_field($result_status, PGSQL_DIAG_SQLSTATE); }
<?php session_start(); include 'conexion.php'; if ($_SERVER['REQUEST_METHOD'] === 'POST') { $query = 'INSERT INTO tiposcontactos (id_tipocontacto, nombre, estado)' . " VALUES ((SELECT cargarRegistro('TiposContactos')),'" . $_POST['tipo_contacto'] . "', true)"; conectarBD(); if (pg_send_query($conexion, $query)) { $resultado = pg_get_result($conexion); if ($resultado) { $estado = pg_result_error_field($resultado, PGSQL_DIAG_SQLSTATE); if ($estado == 0) { // En caso de que no haya ningún error. $_SESSION['error_bd'] = false; $_SESSION['insert_successful'] = true; $_SESSION['success_msg'] = "Contacto agregado exitosamente."; } else { //Hay algún error. $_SESSION['error_bd'] = true; $_SESSION['estado'] = $estado; if ($estado == "23505") { $_SESSION['estado'] = "Violación de valor único"; // Violación de estado único. } } } else { $_SESSION['error_bd'] = true; $_SESSION['estado'] = "Error Desconocido"; } header('Location: mantenimientos.php'); }
/** * @throws DBQueryException * @param ISqlQUery $query * @param boolean $isAsync * @return resource */ protected function performQuery(ISqlQuery $query, $isAsync) { Assert::isBoolean($isAsync); $parameters = $query->getPlaceholderValues($this->getDialect()); $queryAsString = $query->toDialectString($this->getDialect()); if ($isAsync) { LoggerPool::log(parent::LOG_VERBOSE, 'sending an async query: %s', $queryAsString); } else { LoggerPool::log(parent::LOG_VERBOSE, 'sending query: %s', $queryAsString); } LoggerPool::log(parent::LOG_QUERY, $queryAsString); $executeResult = pg_send_query($this->link, $queryAsString); if (!$isAsync || !$executeResult) { $result = pg_get_result($this->link); $resultStatus = pg_result_status($result, PGSQL_STATUS_LONG); if (in_array($resultStatus, array(PGSQL_EMPTY_QUERY, PGSQL_BAD_RESPONSE, PGSQL_NONFATAL_ERROR, PGSQL_FATAL_ERROR))) { $errorCode = pg_result_error_field($result, PGSQL_DIAG_SQLSTATE); $errorMessage = pg_result_error_field($result, PGSQL_DIAG_MESSAGE_PRIMARY); if (PgSqlError::UNIQUE_VIOLATION == $errorCode) { LoggerPool::log(parent::LOG_VERBOSE, 'query caused a unique violation: %s', $errorMessage); throw new UniqueViolationException($query, $errorMessage); } else { LoggerPool::log(parent::LOG_VERBOSE, 'query caused an error #%s: %s', $errorCode, $errorMessage); throw new PgSqlQueryException($query, $errorMessage, $errorCode); } } } return $result; }
private function query($query, $etypeDirty = null) { while (pg_get_result($this->link)) { // Clear the connection of all results. continue; } if (!pg_send_query($this->link, $query)) { throw new Exceptions\QueryFailedException('Query failed: ' . pg_last_error(), 0, null, $query); } if (!($result = pg_get_result($this->link))) { throw new Exceptions\QueryFailedException('Query failed: ' . pg_last_error(), 0, null, $query); } if ($error = pg_result_error_field($result, PGSQL_DIAG_SQLSTATE)) { // If the tables don't exist yet, create them. if ($error == '42P01' && $this->createTables()) { if (isset($etypeDirty)) { $this->createTables($etypeDirty); } if (!($result = pg_query($this->link, $query))) { throw new Exceptions\QueryFailedException('Query failed: ' . pg_last_error(), 0, null, $query); } } else { throw new Exceptions\QueryFailedException('Query failed: ' . pg_last_error(), 0, null, $query); } } return $result; }
/** * Execute the SQL statement. * * @return mixed A database cursor resource on success, boolean false on failure. * * @since 1.0 * @throws \RuntimeException */ public function execute() { $this->connect(); // Take a local copy so that we don't modify the original query and cause issues later $sql = $this->replacePrefix((string) $this->sql); if ($this->limit > 0 || $this->offset > 0) { $sql .= ' LIMIT ' . $this->limit . ' OFFSET ' . $this->offset; } $count = $this->getCount(); // Increment the query counter. $this->count++; // If debugging is enabled then let's log the query. if ($this->debug) { // Add the query to the object queue. $this->log(Log\LogLevel::DEBUG, '{sql}', array('sql' => $sql, 'category' => 'databasequery', 'trace' => debug_backtrace())); } // Reset the error values. $this->errorNum = 0; $this->errorMsg = ''; // Bind the variables if ($this->sql instanceof PreparableInterface) { $bounded =& $this->sql->getBounded(); if (count($bounded)) { // Execute the query. Error suppression is used here to prevent warnings/notices that the connection has been lost. $this->cursor = @pg_execute($this->connection, $this->queryName . $count, array_values($bounded)); } else { // Execute the query. Error suppression is used here to prevent warnings/notices that the connection has been lost. $this->cursor = @pg_query($this->connection, $sql); } } else { // Execute the query. Error suppression is used here to prevent warnings/notices that the connection has been lost. $this->cursor = @pg_query($this->connection, $sql); } // If an error occurred handle it. if (!$this->cursor) { // Check if the server was disconnected. if (!$this->connected()) { try { // Attempt to reconnect. $this->connection = null; $this->connect(); } catch (ConnectionFailureException $e) { // Get the error number and message. $this->errorNum = (int) pg_result_error_field($this->cursor, PGSQL_DIAG_SQLSTATE) . ' '; $this->errorMsg = pg_last_error($this->connection); // Throw the normal query exception. $this->log(Log\LogLevel::ERROR, 'Database query failed (error #{code}): {message}; Failed query: {sql}', array('code' => $this->errorNum, 'message' => $this->errorMsg, 'sql' => $sql)); throw new ExecutionFailureException($sql, $this->errorMsg); } // Since we were able to reconnect, run the query again. return $this->execute(); } else { // Get the error number and message. $this->errorNum = (int) pg_result_error_field($this->cursor, PGSQL_DIAG_SQLSTATE) . ' '; $this->errorMsg = pg_last_error($this->connection) . "\nSQL={$sql}"; // Throw the normal query exception. $this->log(Log\LogLevel::ERROR, 'Database query failed (error #{code}): {message}; Failed query: {sql}', array('code' => $this->errorNum, 'message' => $this->errorMsg, 'sql' => $sql)); throw new ExecutionFailureException($sql, $this->errorMsg); } } return $this->cursor; }
function wpsql_errno($connection) { $result = pg_get_result($connection); $result_status = pg_result_status($result); return pg_result_error_field($result_status, PGSQL_DIAG_SQLSTATE); }
/** * Returns a database error message * * @param string $sql SQL that may have caused the error * @return string Text for error message * */ function dbError($sql = '') { $result = pg_get_result($this->_db); if ($this->_pgsql_version >= 7.4) { // this provides a much more detailed error report if (pg_result_error_field($result, PGSQL_DIAG_SOURCE_LINE)) { $this->_errorlog('You have an error in your SQL query on line ' . pg_result_error_field($result, PGSQL_DIAG_SOURCE_LINE) . "\nSQL in question: {$sql}"); $this->_errorlog('Error: ' . pg_result_error_field($result, PGSQL_DIAG_SQLSTATE) . "\nDescription: " . pg_result_error_field($result, PGSQL_DIAG_MESSAGE_DETAIL)); if ($this->_display_error) { $error = "An SQL error has occurred in the following SQL: {$sql}"; } else { $error = 'An SQL error has occurred. Please see error.log for details.'; } return $error; } } else { if (pg_result_error($result)) { $this->_errorlog(pg_result_error($result) . ". SQL in question: {$sql}"); if ($this->_display_error) { $error = 'Error ' . pg_result_error($result); } else { $error = 'An SQL error has occurred. Please see error.log for details.'; } return $error; } } return; }
/** * Execute the SQL statement. * * @return mixed A database cursor resource on success, boolean false on failure. * * @since 12.1 * @throws RuntimeException */ public function execute() { $this->connect(); if (!is_resource($this->connection)) { JLog::add(JText::sprintf('JLIB_DATABASE_QUERY_FAILED', $this->errorNum, $this->errorMsg), JLog::ERROR, 'database'); throw new RuntimeException($this->errorMsg, $this->errorNum); } // Take a local copy so that we don't modify the original query and cause issues later $sql = $this->replacePrefix((string) $this->sql); if ($this->limit > 0 || $this->offset > 0) { $sql .= ' LIMIT ' . $this->limit . ' OFFSET ' . $this->offset; } // Increment the query counter. $this->count++; // If debugging is enabled then let's log the query. if ($this->debug) { // Add the query to the object queue. $this->log[] = $sql; JLog::add($sql, JLog::DEBUG, 'databasequery'); } // Reset the error values. $this->errorNum = 0; $this->errorMsg = ''; // Execute the query. Error suppression is used here to prevent warnings/notices that the connection has been lost. $this->cursor = @pg_query($this->connection, $sql); // If an error occurred handle it. if (!$this->cursor) { // Check if the server was disconnected. if (!$this->connected()) { try { // Attempt to reconnect. $this->connection = null; $this->connect(); } // If connect fails, ignore that exception and throw the normal exception. catch (RuntimeException $e) { // Get the error number and message. $this->errorNum = (int) pg_result_error_field($this->cursor, PGSQL_DIAG_SQLSTATE) . ' '; $this->errorMsg = JText::_('JLIB_DATABASE_QUERY_FAILED') . "\n" . pg_last_error($this->connection) . "\nSQL=$sql"; // Throw the normal query exception. JLog::add(JText::sprintf('JLIB_DATABASE_QUERY_FAILED', $this->errorNum, $this->errorMsg), JLog::ERROR, 'databasequery'); throw new RuntimeException($this->errorMsg); } // Since we were able to reconnect, run the query again. return $this->execute(); } // The server was not disconnected. else { // Get the error number and message. $this->errorNum = (int) pg_result_error_field($this->cursor, PGSQL_DIAG_SQLSTATE) . ' '; $this->errorMsg = JText::_('JLIB_DATABASE_QUERY_FAILED') . "\n" . pg_last_error($this->connection) . "\nSQL=$sql"; // Throw the normal query exception. JLog::add(JText::sprintf('JLIB_DATABASE_QUERY_FAILED', $this->errorNum, $this->errorMsg), JLog::ERROR, 'databasequery'); throw new RuntimeException($this->errorMsg); } } return $this->cursor; }
function sql_query($query = "", $transaction = false) { // // Remove any pre-existing queries // unset($this->query_result); if ($query != "") { $this->num_queries++; $query = preg_replace("/LIMIT ([0-9]+),([ 0-9]+)/", "LIMIT \\2 OFFSET \\1", $query); if ($transaction == BEGIN_TRANSACTION && !$this->in_transaction) { $this->in_transaction = TRUE; if (!@pg_query($this->db_connect_id, "BEGIN")) { return false; } } //echo "DB" ;print_r($this); if (pg_send_query($this->db_connect_id, $query)) { $this->query_result = pg_get_result($this->db_connect_id); $error_code = pg_result_error_field($this->query_result, PGSQL_DIAG_SQLSTATE); } //$this->query_result = @pg_query($this->db_connect_id, $query); if (!$error_code) { if ($transaction == END_TRANSACTION) { $this->in_transaction = FALSE; if (!@pg_query($this->db_connect_id, "COMMIT")) { @pg_query($this->db_connect_id, "ROLLBACK"); return false; } } $this->last_query_text[$this->query_result] = $query; $this->rownum[$this->query_result] = 0; unset($this->row[$this->query_result]); unset($this->rowset[$this->query_result]); return $this->query_result; } else { if ($this->in_transaction) { @pg_query($this->db_connect_id, "ROLLBACK"); } $this->in_transaction = FALSE; /*pg_send_query($this->db_connect_id, $query); $result = pg_get_result($this->db_connect_id); $code=pg_result_error_field($result, PGSQL_DIAG_SQLSTATE);*/ $this->error_message[] = array("code" => $error_code, "text" => pg_result_error($this->query_result), "query" => $query); return false; } } else { if ($transaction == END_TRANSACTION && $this->in_transaction) { $this->in_transaction = FALSE; if (!@pg_query($this->db_connect_id, "COMMIT")) { @pg_query($this->db_connect_id, "ROLLBACK"); return false; } } return true; } }
/** * Prints error message $error to debug system. * @param string $query The query that was attempted, will be printed if * $error is \c false * @param PDOStatement|resource $res The result resource the error occurred on * @param string $fname The function name that started the query, should * contain relevant arguments in the text. * @param string $error The error message, if this is an array the first * element is the value to dump and the second the error * header (for eZDebug::writeNotice). If this is \c * false a generic message is shown. */ protected function _error($query, $res, $fname, $error = "Failed to execute SQL for function:") { if ($error === false) { $error = "Failed to execute SQL for function:"; } else { if (is_array($error)) { $fname = $error[1]; $error = $error[0]; } } // @todo Investigate error methods eZDebug::writeError("{$error}\n" . pg_result_error_field($res, PGSQL_DIAG_SQLSTATE) . ': ' . pg_result_error_field($res, PGSQL_DIAG_MESSAGE_PRIMARY) . ' ' . $query, $fname); }
/** Returns the primary key index value. @param $sName The primary key index name, if needed. @return string The primary key index value. @throw IllegalStateException No value has been generated yet for the given sequence in this session. */ public function getPKId($sName = null) { if ($sName === null) { $sQuery = 'SELECT pg_catalog.lastval()'; } else { $sQuery = 'SELECT pg_catalog.currval(' . $this->escape($sName) . ')'; } // We need to get the SQLSTATE returned by PostgreSQL so we can't use pg_query here. pg_send_query($this->rLink, $sQuery); $r = pg_get_result($this->rLink); $mSQLState = pg_result_error_field($r, PGSQL_DIAG_SQLSTATE); $mSQLState == '55000' and burn('IllegalStateException', _WT('PostgreSQL has not yet generated a value for the given sequence in this session.')); $mSQLState === null or burn('DatabaseException', sprintf(_WT("PostgreSQL failed to return the value of the given sequence with the following message:\n%s"), pg_last_error($this->rLink))); return pg_fetch_result($r, 0, 0); }
/** * This method is the central method for handling database * interaction. The method can be used for setting up a database * connection, for running a SQL query and for returning query rows. * Which of these actions the method will handle and what the method * return data will be, is determined by the $return method parameter. * * @param $return - What to return. Options are the following constants: * DB_RETURN_CONN a db connection handle * DB_RETURN_QUOTED a quoted parameter * DB_RETURN_RES result resource handle * DB_RETURN_ROW single row as array * DB_RETURN_ROWS all rows as arrays * DB_RETURN_ASSOC single row as associative array * DB_RETURN_ASSOCS all rows as associative arrays * DB_RETURN_VALUE single row, single column * DB_RETURN_ROWCOUNT number of selected rows * DB_RETURN_NEWID new row id for insert query * DB_RETURN_ERROR an error message if the query * failed or NULL if there was * no error * DB_CLOSE_CONN close the connection, no * return data * * @param $sql - The SQL query to run or the parameter to quote if * DB_RETURN_QUOTED is used. * * @param $keyfield - When returning an array of rows, the indexes are * numerical by default (0, 1, 2, etc.). However, if * the $keyfield parameter is set, then from each * row the $keyfield index is taken as the key for the * return array. This way, you can create a direct * mapping between some id field and its row in the * return data. Mind that there is no error checking * at all, so you have to make sure that you provide * a valid $keyfield here! * * @param $flags - Special flags for modifying the method's behavior. * These flags can be OR'ed if multiple flags are needed. * DB_NOCONNECTOK Failure to connect is not fatal * but lets the call return FALSE * (useful in combination with * DB_RETURN_CONN). * DB_MISSINGTABLEOK Missing table errors not fatal. * DB_DUPFIELDNAMEOK Duplicate field errors not fatal. * DB_DUPKEYNAMEOK Duplicate key name errors * not fatal. * DB_DUPKEYOK Duplicate key errors not fatal. * * @param $limit - The maximum number of rows to return. * @param $offset - The number of rows to skip in the result set, * before returning rows to the caller. * * @return $res - The result of the query, based on the $return * parameter. */ public function interact($return, $sql = NULL, $keyfield = NULL, $flags = 0, $limit = 0, $offset = 0) { global $PHORUM; static $conn; // Close the database connection. if ($return == DB_CLOSE_CONN) { if (!empty($conn)) { pg_close($conn); $conn = null; } return; } // Setup a database connection if no database connection is // available yet. if (empty($conn)) { // Format the connection string for pg_connect. $conn_string = ''; if ($PHORUM['DBCONFIG']['server']) { $conn_string .= ' host=' . $PHORUM['DBCONFIG']['server']; } if ($PHORUM['DBCONFIG']['user']) { $conn_string .= ' user='******'DBCONFIG']['user']; } if ($PHORUM['DBCONFIG']['password']) { $conn_string .= ' password='******'DBCONFIG']['password']; } if ($PHORUM['DBCONFIG']['name']) { $conn_string .= ' dbname=' . $PHORUM['DBCONFIG']['name']; } // Try to setup a connection to the database. $conn = @pg_connect($conn_string, PGSQL_CONNECT_FORCE_NEW); if ($conn === FALSE) { if ($flags & DB_NOCONNECTOK) { return FALSE; } phorum_api_error(PHORUM_ERRNO_DATABASE, 'Failed to connect to the database.'); exit; } if (!empty($PHORUM['DBCONFIG']['charset'])) { $charset = $PHORUM['DBCONFIG']['charset']; pg_query($conn, "SET CLIENT_ENCODING TO '{$charset}'"); } } // RETURN: quoted parameter. if ($return === DB_RETURN_QUOTED) { return pg_escape_string($conn, $sql); } // RETURN: database connection handle. if ($return === DB_RETURN_CONN) { return $conn; } // By now, we really need a SQL query. if ($sql === NULL) { trigger_error(__METHOD__ . ': Internal error: ' . 'missing sql query statement!', E_USER_ERROR); } // Apply limit and offset to the query. settype($limit, 'int'); settype($offset, 'int'); if ($limit > 0) { $sql .= " LIMIT {$limit}"; } if ($offset > 0) { $sql .= " OFFSET {$offset}"; } // Execute the SQL query. if (!@pg_send_query($conn, $sql)) { trigger_error(__METHOD__ . ': Internal error: ' . 'pg_send_query() failed!', E_USER_ERROR); } // Check if an error occurred. $res = pg_get_result($conn); $errno = pg_result_error_field($res, PGSQL_DIAG_SQLSTATE); if ($errno != 0) { // See if the $flags tell us to ignore the error. $ignore_error = FALSE; switch ($errno) { // Table does not exist. case '42P01': if ($flags & DB_MISSINGTABLEOK) { $ignore_error = TRUE; } break; // Table already exists or duplicate key name. // These two cases use the same error code. // Table already exists or duplicate key name. // These two cases use the same error code. case '42P07': if ($flags & DB_TABLEEXISTSOK) { $ignore_error = TRUE; } if ($flags & DB_DUPKEYNAMEOK) { $ignore_error = TRUE; } break; // Duplicate column name. // Duplicate column name. case '42701': if ($flags & DB_DUPFIELDNAMEOK) { $ignore_error = TRUE; } break; // Duplicate entry for key. // Duplicate entry for key. case '23505': if ($flags & DB_DUPKEYOK) { $ignore_error = TRUE; # the code expects res to have no value upon error $res = NULL; } break; } // Handle this error if it's not to be ignored. if (!$ignore_error) { $errmsg = pg_result_error($res); // RETURN: error message if ($return === DB_RETURN_ERROR) { return $errmsg; } // Trigger an error. phorum_api_error(PHORUM_ERRNO_DATABASE, "{$errmsg} ({$errno}): {$sql}"); exit; } } // RETURN: NULL (no error) if ($return === DB_RETURN_ERROR) { return NULL; } // RETURN: query resource handle if ($return === DB_RETURN_RES) { return $res; } // RETURN: number of rows if ($return === DB_RETURN_ROWCOUNT) { return $res ? pg_num_rows($res) : 0; } // RETURN: array rows or single value if ($return === DB_RETURN_ROW || $return === DB_RETURN_ROWS || $return === DB_RETURN_VALUE) { // Keyfields are only valid for DB_RETURN_ROWS. if ($return !== DB_RETURN_ROWS) { $keyfield = NULL; } $rows = array(); if ($res) { while ($row = pg_fetch_row($res)) { if ($keyfield === NULL) { $rows[] = $row; } else { $rows[$row[$keyfield]] = $row; } } } // Return all rows. if ($return === DB_RETURN_ROWS) { return $rows; } // Return a single row. if ($return === DB_RETURN_ROW) { if (count($rows) == 0) { return NULL; } else { return $rows[0]; } } // Return a single value. if (count($rows) == 0) { return NULL; } else { return $rows[0][0]; } } // RETURN: associative array rows if ($return === DB_RETURN_ASSOC || $return === DB_RETURN_ASSOCS) { // Keyfields are only valid for DB_RETURN_ASSOCS. if ($return !== DB_RETURN_ASSOCS) { $keyfield = NULL; } $rows = array(); if ($res) { while ($row = pg_fetch_assoc($res)) { if ($keyfield === NULL) { $rows[] = $row; } else { $rows[$row[$keyfield]] = $row; } } } // Return all rows. if ($return === DB_RETURN_ASSOCS) { return $rows; } // Return a single row. if ($return === DB_RETURN_ASSOC) { if (count($rows) == 0) { return NULL; } else { return $rows[0]; } } } // RETURN: new id after inserting a new record if ($return === DB_RETURN_NEWID) { $res = pg_exec($conn, "SELECT lastval()"); if ($res === FALSE) { phorum_api_error(PHORUM_ERRNO_DATABASE, 'Failed to get a lastval() result.'); } $row = pg_fetch_row($res); if ($row === FALSE) { phorum_api_error(PHORUM_ERRNO_DATABASE, 'No rows returned from LASTVAL().'); } return $row[0]; } trigger_error(__METHOD__ . ': Internal error: ' . 'illegal return type specified!', E_USER_ERROR); }
/** * Return the actual SQL Error number * * @return integer The SQL Error number * * @since 3.4.6 */ protected function getErrorNumber() { return (int) pg_result_error_field($this->cursor, PGSQL_DIAG_SQLSTATE) . ' '; }
if (function_exists('pg_result_error_field')) { pg_result_error_field($result, PGSQL_DIAG_SEVERITY); pg_result_error_field($result, PGSQL_DIAG_SQLSTATE); pg_result_error_field($result, PGSQL_DIAG_MESSAGE_PRIMARY); pg_result_error_field($result, PGSQL_DIAG_MESSAGE_DETAIL); pg_result_error_field($result, PGSQL_DIAG_MESSAGE_HINT); pg_result_error_field($result, PGSQL_DIAG_STATEMENT_POSITION); if (defined('PGSQL_DIAG_INTERNAL_POSITION')) { pg_result_error_field($result, PGSQL_DIAG_INTERNAL_POSITION); } if (defined('PGSQL_DIAG_INTERNAL_QUERY')) { pg_result_error_field($result, PGSQL_DIAG_INTERNAL_QUERY); } pg_result_error_field($result, PGSQL_DIAG_CONTEXT); pg_result_error_field($result, PGSQL_DIAG_SOURCE_FILE); pg_result_error_field($result, PGSQL_DIAG_SOURCE_LINE); pg_result_error_field($result, PGSQL_DIAG_SOURCE_FUNCTION); } pg_num_rows(pg_query($db, "SELECT * FROM " . $table_name . ";")); pg_num_fields(pg_query($db, "SELECT * FROM " . $table_name . ";")); pg_field_name($result, 0); pg_field_num($result, $field_name); pg_field_size($result, 0); pg_field_type($result, 0); pg_field_prtlen($result, 0); pg_field_is_null($result, 0); $result = pg_query($db, "INSERT INTO " . $table_name . " VALUES (9999, 'ABC');"); pg_last_oid($result); pg_free_result($result); pg_close($db); echo "OK";
/** * Returns a database error message * * @param string $sql SQL that may have caused the error * @return string Text for error message * */ function dbError($sql = '') { $fn = ''; $btr = debug_backtrace(); if (!empty($btr)) { for ($i = 0; $i < count($btr); $i++) { if (isset($btr[$i])) { $b = $btr[$i]; if ($b['function'] == 'DB_query') { if (!empty($b['file']) && !empty($b['line'])) { $fn = $b['file'] . ':' . $b['line']; } break; } } else { break; } } if (!empty($fn)) { $fn = ' in ' . $fn; } } $result = pg_get_result($this->_db); if ($this->_pgsql_version >= 7.4) { // this provides a much more detailed error report if (pg_result_error_field($result, PGSQL_DIAG_SOURCE_LINE)) { $this->_errorlog('You have an error in your SQL query on line ' . pg_result_error_field($result, PGSQL_DIAG_SOURCE_LINE) . "{$fn}\nSQL in question: {$sql}"); $this->_errorlog('Error: ' . pg_result_error_field($result, PGSQL_DIAG_SQLSTATE) . "{$fn}\nDescription: " . pg_result_error_field($result, PGSQL_DIAG_MESSAGE_DETAIL)); if ($this->_display_error) { $error = "An SQL error has occurred in the following SQL: {$sql}"; } else { $error = 'An SQL error has occurred. Please see error.log for details.'; } return $error; } } else { if (pg_result_error($result)) { $this->_errorlog(pg_result_error($result) . "{$fn}. SQL in question: {$sql}"); if ($this->_display_error) { $error = 'Error ' . pg_result_error($result); } else { $error = 'An SQL error has occurred. Please see error.log for details.'; } return $error; } } return; }
/** * Complete query * @param string $query query string * @param array|null $data query parameters * @return QueryResult postgres query result * @throws DuplicateEntryException when entry was duplicated * @throws DuplicateTableException when table was duplicated * @throws ConnectionBusyException when connection busy by another request * @throws UndefinedTableException when try to query undefined table * @throws QueryException for other reasons */ public function query($query, array $data = null) { if (is_null($this->Resource)) { $this->connect(); } $busy = false; if ($this->needBusyCheckup()) { $busy = pg_connection_busy($this->Resource); } if (!$busy) { $this->sendQuery($query, $data); $Result = pg_get_result($this->Resource); $Error = pg_result_error($Result); if (!empty($Error)) { $errorMessage = pg_errormessage($this->Resource); $errorCode = pg_result_error_field($Result, PGSQL_DIAG_SQLSTATE); switch ($errorCode) { case self::CODE_DUPLICATE_ENTRY: throw new DuplicateEntryException($errorMessage); case self::CODE_UNDEFINED_TABLE: throw new UndefinedTableException($errorMessage); case self::CODE_DUPLICATE_TABLE: throw new DuplicateTableException($errorMessage); case self::CODE_DUPLICATE_TYPE: throw new DuplicateTypeException($errorMessage); case self::CODE_RAISE_EXCEPTION: throw new RaiseException($errorMessage); default: throw new QueryException(sprintf("%s QUERY: %s CODE: %s", $errorMessage, $query, $errorCode)); } } else { return new QueryResult($Result); } } else { throw new ConnectionBusyException(); } }
$pgarraystr3 = '{"geo","true",' . '"' . $search_id_geo . '",' . '"' . $geoexclude . '"}'; } else { $pgarraystr3 = '{"geo","false",' . '"' . $search_id_geo . '",' . '"' . $geoexclude . '"}'; } if ($Report['Rated'] == true) { $strgqry = $strgqry . 'SELECT serviceprovider_id FROM techmatcher.ratingevents where ratingtotal>0'; $reportrated = 'true'; } else { $reportrated = 'false'; } $resultid = 0; $qry = 'select techmatcher.matchhandler(' . $it_consumer . ',\'' . '\',\'' . $finalflag . '\',' . '\'{' . $pgarraystr1 . ',' . $pgarraystr2 . ',' . $pgarraystr3 . ' }\',' . '\'' . $reportrated . '\',\'' . $ratingexclude . '\')' or die(pg_errormessage()); if (pg_query($qry) == FALSE) { $match_result = pg_send_query($dbconn, $qry); $res1 = pg_get_result($dbconn); $error_field_description = pg_result_error_field($res1, PGSQL_DIAG_MESSAGE_PRIMARY); echo $error_field_description; } else { //match_result=pg_query($qry); $resultid = pg_result(pg_query($qry), 0, 0); //$resultid=pg_result($match_result, 0,0); } $qry = "select sp.serviceprovider_id, sp.primaryname\r\n from techmatcher.lastmatch_vw as lmv, techmatcher.matchhistory as mh,techmatcher.serviceprovider as sp\r\n where lmv.search_id = mh.search_id and mh.serviceprovider_id = sp.serviceprovider_id\r\n and mh.search_id=\$1\r\n GROUP by sp.serviceprovider_id, sp.primaryname"; if ($resultid != 0) { $resulting2 = pg_query_params($qry, array($resultid)); while ($name = pg_fetch_assoc($resulting2)) { $names[] = $name; $record_counter++; } echo 'OK'; }
/** * Execute the SQL statement. * * @return mixed A database cursor resource on success, boolean false on failure. * * @throws \RuntimeException */ public function query() { $this->open(); if (!is_resource($this->connection)) { throw new \RuntimeException($this->errorMsg, $this->errorNum); } // Take a local copy so that we don't modify the original query and cause issues later $query = $this->replacePrefix((string) $this->sql); if ($this->limit > 0 || $this->offset > 0) { $query .= ' LIMIT ' . $this->limit . ' OFFSET ' . $this->offset; } // Increment the query counter. $this->count++; // If debugging is enabled then let's log the query. if ($this->debug) { // Add the query to the object queue. $this->log[] = $query; } // Reset the error values. $this->errorNum = 0; $this->errorMsg = ''; // Execute the query. Error suppression is used here to prevent warnings/notices that the connection has been lost. $this->cursor = @pg_query($this->connection, $query); // If an error occurred handle it. if (!$this->cursor) { // Get the error number and message before we overwrite the error message $this->errorNum = (int) pg_result_error_field($this->cursor, PGSQL_DIAG_SQLSTATE) . ' '; // This will never wok as the cursor is false $this->errorMsg = pg_last_error($this->connection) . " SQL=" . $query; // Check if the server was disconnected. if (!$this->connected()) { try { // Attempt to reconnect. $this->connection = null; $this->open(); } catch (\RuntimeException $e) { // Get the error number and message. $this->errorNum = (int) pg_result_error_field($this->cursor, PGSQL_DIAG_SQLSTATE) . ' '; // This will never wok as the cursor is false $this->errorMsg = pg_last_error($this->connection); // Throw the normal query exception. throw new \RuntimeException($this->errorMsg); } // Since we were able to reconnect, run the query again. return $this->execute(); } else { // Throw the normal query exception. throw new \RuntimeException($this->errorMsg); } } return $this->cursor; }
function getQueryError($result) { return pg_result_error_field($result, PGSQL_DIAG_SQLSTATE); }
/** * Execute the SQL statement. * * @return mixed A database cursor resource on success, boolean false on failure. * * @since 12.1 * @throws RuntimeException */ public function execute() { $this->connect(); if (!is_resource($this->connection)) { JLog::add(JText::sprintf('JLIB_DATABASE_QUERY_FAILED', $this->errorNum, $this->errorMsg), JLog::ERROR, 'database'); throw new RuntimeException($this->errorMsg, $this->errorNum); } // Take a local copy so that we don't modify the original query and cause issues later $query = $this->replacePrefix((string) $this->sql); if (!$this->sql instanceof JDatabaseQuery && ($this->limit > 0 || $this->offset > 0)) { $query .= ' LIMIT ' . $this->limit . ' OFFSET ' . $this->offset; } // Increment the query counter. $this->count++; // Reset the error values. $this->errorNum = 0; $this->errorMsg = ''; // If debugging is enabled then let's log the query. if ($this->debug) { // Add the query to the object queue. $this->log[] = $query; JLog::add($query, JLog::DEBUG, 'databasequery'); $this->timings[] = microtime(true); } // Execute the query. Error suppression is used here to prevent warnings/notices that the connection has been lost. $this->cursor = @pg_query($this->connection, $query); if ($this->debug) { $this->timings[] = microtime(true); if (defined('DEBUG_BACKTRACE_IGNORE_ARGS')) { $this->callStacks[] = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); } else { $this->callStacks[] = debug_backtrace(); } } // If an error occurred handle it. if (!$this->cursor) { // Check if the server was disconnected. if (!$this->connected()) { try { // Attempt to reconnect. $this->connection = null; $this->connect(); } catch (RuntimeException $e) { // Get the error number and message. $this->errorNum = (int) pg_result_error_field($this->cursor, PGSQL_DIAG_SQLSTATE) . ' '; $this->errorMsg = pg_last_error($this->connection) . "SQL=" . $query; // Throw the normal query exception. JLog::add(JText::sprintf('JLIB_DATABASE_QUERY_FAILED', $this->errorNum, $this->errorMsg), JLog::ERROR, 'database-error'); throw new RuntimeException($this->errorMsg); } // Since we were able to reconnect, run the query again. return $this->execute(); } else { // Get the error number and message. $this->errorNum = (int) pg_result_error_field($this->cursor, PGSQL_DIAG_SQLSTATE) . ' '; $this->errorMsg = pg_last_error($this->connection) . "SQL=" . $query; // Throw the normal query exception. JLog::add(JText::sprintf('JLIB_DATABASE_QUERY_FAILED', $this->errorNum, $this->errorMsg), JLog::ERROR, 'database-error'); throw new RuntimeException($this->errorMsg); } } return $this->cursor; }
while ($row = pg_fetch_row($result)) { //echo "Password: $row[0]"; $password = $row[0]; } //Check to see if database password matches the Posted password, if so do not update the password, else delete user and re-insert the user with encrypted password if ($password === $_POST['userPassword']) { $sql = "UPDATE {$schema_name}.users SET first_name='{$_POST['firstName']}', last_name='{$_POST['lastName']}', \r\n\t\t\t\t\t\temail='{$_POST['userEmail']}', phone='{$_POST['userPhone']}', \r\n\t\t\t\t\t\tusername='******'userName']}', security='{$_POST['userSecurity']}' WHERE id='{$_POST['userId']}' "; //echo "<script type='text/javascript'>alert('$sql');</script>"; pg_query($dbconn, $sql); echo "Updated " . $_POST['userName'] . " Successfully!"; } else { //echo 'Password Was Changed.....'; //echo $password.'<br/>'.$_POST['userPassword'].'<br/>'; //Delete User info $delSql = "DELETE FROM {$schema_name}.users WHERE id='{$_POST['userId']}'"; pg_query($dbconn, $delSql); //echo '<br/>'.$delSql.'<br/>'; //Insert all the new records for the user $sql = "INSERT INTO {$schema_name}.users(id, first_name, last_name, email, phone, username, pwd, security)\r\n\t \t\t\tVALUES ('{$_POST['userId']}','{$_POST['firstName']}', '{$_POST['lastName']}', '{$_POST['userEmail']}', '{$_POST['userPhone']}', '{$_POST['userName']}', crypt('{$_POST['userPassword']}', gen_salt('bf')), '{$_POST['userSecurity']}')"; pg_query($dbconn, $sql); echo "Updated " . $_POST['userName'] . " Successfully!"; } } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; //catch error if exists $res1 = pg_get_result($dbconn); echo pg_result_error_field($res1, PGSQL_DIAG_SQLSTATE); } break; } }
function lastErrno() { if ($this->mLastResult) { return pg_result_error_field($this->mLastResult, PGSQL_DIAG_SQLSTATE); } else { return false; } }
/** * Executes the query that was previously passed to the constructor. * * @param mixed $arg Query arguments to escape and insert at ? placeholders in $query * @param mixed ... Additional arguments **/ public function execute() { // We can't very well perform a query wtihout an active connection. if ($this->dbh === false || pg_connection_status($this->dbh) !== PGSQL_CONNECTION_OK) { $this->db->error('Lost connection to database.'); return; } // Finish any previous statements $this->finish(); // We need to pre-process the arguments for literals and bytefields. We // can't safely pass them into the naitve placeholder system, so we'll // have to stick them into the query at the right places before then. // Additionally, PG uses the string values 't' and 'f' for boolean true // and false, and will choke over PHP true/false when passed in this way. $args = Database::smart_args(func_get_args()); foreach ($args as $i => $arg) { if (is_bool($arg)) { $args[$i] = $arg === true ? 't' : 'f'; } } list($query, $nargs, $nargn) = $this->reprocess_query($args); if (!$query) { return; } // Prepare the placeholders. PG uses $1, $2 .. $n as their placeholders. // Continuing the example from Database_Query::reprocess_query, we should // have the following $query array: // 'SELECT * FROM table WHERE a = ', // ' AND b < NOW() AND c > ' // which will get turned into the following string: // SELECT * FROM table WHERE a = $1 AND b < NOW() AND c > $2 $this->last_query = ''; $placeholder_count = 1; foreach ($query as $i => $chunk) { $this->last_query .= $chunk; if ($placeholder_count <= $nargn) { $this->last_query .= '$' . $placeholder_count; $placeholder_count++; } } // Wrap the actual query execution in a bit of benchmarking. $before = microtime(true); // We're only using placeholders here, not prepared statements. Why not? // The possibility of missing / pre-replaced placeholders means that the // actual query we get to execute changes each time. $this->sh = false; $this->errno = null; $state = pg_send_query_params($this->dbh, $this->last_query, $nargs); if ($state) { // So, here's some fun. Like PDO, PG has error reporting bits at both // the top level and at the statement level. However, the normal // query method returns false instead of a statement handle, and we // need the statement handle to pull errors back. This means that // we need to use the async query sending method and check every single // time for an error message. We can then nuke the statement handle // so things that try to look for it to detect errors can work. $this->sh = pg_get_result($this->dbh); $sqlstate = pg_result_error_field($this->sh, PGSQL_DIAG_SQLSTATE); if ($sqlstate && $sqlstate != '00000') { $this->errno = $sqlstate; $this->errstr = pg_result_error_field($this->sh, PGSQL_DIAG_MESSAGE_PRIMARY) . ' [detail=' . pg_result_error_field($this->sh, PGSQL_DIAG_MESSAGE_DETAIL) . '] (hint=' . pg_result_error_field($this->sh, PGSQL_DIAG_MESSAGE_HINT) . ') at character ' . pg_result_error_field($this->sh, PGSQL_DIAG_STATEMENT_POSITION); $this->sh = false; } } else { $this->db->error('Could not send query to server.'); return; } $after = microtime(true); $this->db->mysql_time += $after - $before; // The other adapters also fetch the last insert id here, which we can't // effectively do, as it's not exposed by PG. As an alternative, you can // use a RETURNING clause in your query to fetch generated values: // INSERT INTO table(foo, bar) VALUES(?, ?) RETURNING id; if (is_bool($this->sh) || is_null($this->sh)) { $this->affected_rows = 0; $this->num_rows = 0; } elseif (is_resource($this->sh)) { $this->affected_rows = pg_affected_rows($this->sh); $this->num_rows = pg_num_rows($this->sh); } else { assert('false; // statement handler was not a bool or resource, it was a: ' . gettype($this->sh)); } // Upstream code may care about warnings. PG can return multiple notices // for any given query. It's unclear whether or not this will work, as // I haven't been able to actually find any query that does emit multiple // notices. If your code suddenly launches into an infinite loop, now you // know why. Fun times indeed. if ($this->db->enable_warning_logging) { $this->warnings = array(); while (($last_notice = pg_last_notice($this->dbh)) !== false) { $this->warnings[] = $last_notice; } $GLOBALS['_DEBUG']['Database Warnings'][] = array('Query' => $this->last_query, 'Warnings' => $this->warnings); } // Finally, did it even work? if ($this->sh === false) { $this->db->error('SQL Error:'); return false; } return true; }