Example #1
0
function safe_dml_query($query, $verbose = True)
{
    global $conn;
    if ($verbose) {
        echo "------------------------\n";
        echo "Executing PG query: {$query}\n";
    }
    $time_start = microtime(true);
    pg_send_query($conn, $query) or die("Failed to execute query {$query}");
    while (pg_connection_busy($conn)) {
        if (microtime(true) - $time_start > 30) {
            if (rand(0, 10) == 0) {
                echo "Busy for " . round((microtime(true) - $time_start) * 1000) . " ms -";
            }
            sleep(5);
        }
        usleep(2000);
    }
    $res = pg_get_result($conn);
    if (pg_result_error($res) != null) {
        die("Error during query: " . pg_result_error($res) . "\n");
    }
    $time_end = microtime(true);
    $rows = pg_affected_rows($res);
    if ($verbose) {
        echo "Done executing {$query}: {$rows} touched\n";
        $t = round(($time_end - $time_start) * 1000);
        echo "Query time: {$t} ms\n";
        echo "------------------------\n";
    }
}
Example #2
0
 public function __construct($result, $sql, $as_object = FALSE, $params = NULL, $total_rows = NULL)
 {
     parent::__construct($result, $sql, $as_object, $params);
     if ($as_object === TRUE) {
         $this->_as_object = 'stdClass';
     }
     if ($total_rows !== NULL) {
         $this->_total_rows = $total_rows;
     } else {
         switch (pg_result_status($result)) {
             case PGSQL_TUPLES_OK:
                 $this->_total_rows = pg_num_rows($result);
                 break;
             case PGSQL_COMMAND_OK:
                 $this->_total_rows = pg_affected_rows($result);
                 break;
             case PGSQL_BAD_RESPONSE:
             case PGSQL_NONFATAL_ERROR:
             case PGSQL_FATAL_ERROR:
                 throw new Database_Exception(':error [ :query ]', array(':error' => pg_result_error($result), ':query' => $sql));
             case PGSQL_COPY_OUT:
             case PGSQL_COPY_IN:
                 throw new Database_Exception('PostgreSQL COPY operations not supported [ :query ]', array(':query' => $sql));
             default:
                 $this->_total_rows = 0;
         }
     }
 }
Example #3
0
 public function query($sql)
 {
     $resource = pg_query($this->link, $sql);
     if ($resource) {
         if (is_resource($resource)) {
             $i = 0;
             $data = array();
             while ($result = pg_fetch_assoc($resource)) {
                 $data[$i] = $result;
                 $i++;
             }
             pg_free_result($resource);
             $query = new \stdClass();
             $query->row = isset($data[0]) ? $data[0] : array();
             $query->rows = $data;
             $query->num_rows = $i;
             unset($data);
             return $query;
         } else {
             return true;
         }
     } else {
         trigger_error('Error: ' . pg_result_error($this->link) . '<br />' . $sql);
         exit;
     }
 }
 /**
  * @param   resource    from pg_query() or pg_get_result()
  * @param   string      SQL used to create this result
  * @param   resource    from pg_connect() or pg_pconnect()
  * @param   boolean|string
  * @return  void
  */
 public function __construct($result, $sql, $link, $return_objects)
 {
     // PGSQL_COMMAND_OK     <- SET client_encoding = 'utf8'
     // PGSQL_TUPLES_OK      <- SELECT table_name FROM information_schema.tables
     // PGSQL_COMMAND_OK     <- INSERT INTO pages (name) VALUES ('gone soon')
     // PGSQL_COMMAND_OK     <- DELETE FROM pages WHERE id = 2
     // PGSQL_COMMAND_OK     <- UPDATE pb_users SET company_id = 1
     // PGSQL_FATAL_ERROR    <- SELECT FROM pages
     switch (pg_result_status($result)) {
         case PGSQL_EMPTY_QUERY:
             $this->total_rows = 0;
             break;
         case PGSQL_COMMAND_OK:
             $this->total_rows = pg_affected_rows($result);
             break;
         case PGSQL_TUPLES_OK:
             $this->total_rows = pg_num_rows($result);
             break;
         case PGSQL_COPY_OUT:
         case PGSQL_COPY_IN:
             Kohana_Log::add('debug', 'PostgreSQL COPY operations not supported');
             break;
         case PGSQL_BAD_RESPONSE:
         case PGSQL_NONFATAL_ERROR:
         case PGSQL_FATAL_ERROR:
             throw new Database_Exception(':error [ :query ]', array(':error' => pg_result_error($result), ':query' => $sql));
     }
     $this->link = $link;
     $this->result = $result;
     $this->return_objects = $return_objects;
     $this->sql = $sql;
 }
Example #5
0
 public static function conn_db($dbdata)
 {
     if (is_array($dbdata)) {
         extract($dbdata[Db::$dbconn]);
         Db::$db = @$dbtype;
     }
     $error = '';
     switch (Db::$db) {
         case 'Pg':
             $con = pg_connect("host={$host} port={$port} dbname={$database} user={$user} password={$password}") or die("{$error}=" . pg_result_error());
             break;
         case 'Mysql':
             $con = mysql_connect($host . ':' . $port, $user, $password);
             mysql_select_db($database) or die("{$error}=" . mysql_error());
             break;
         case 'Oci':
             $con = oci_connect($user, $password, $host . ':' . $port . '/' . $database);
             if (!$con) {
                 $error = oci_error();
                 trigger_error(htmlentities($error['message'], ENT_QUOTES), E_USER_ERROR);
             }
             break;
     }
     if ($error != '') {
         $con = $error;
     }
     return $con;
 }
 /**
  * Method to send SQL query
  *
  * @param   resource    $res_conn
  * @return  void
  */
 private function sendQuery($res_conn)
 {
     // checking query type
     // if the query return recordset or not
     if (preg_match("/^(SELECT)\\s/i", $this->sql_string)) {
         $this->res_result = @pg_query($res_conn, $this->sql_string);
         // error checking
         if (!$this->res_result) {
             $this->errno = 1;
             $this->error = "Query failed to executed. Please check your query again. \n" . pg_result_error($this->res_result);
         } else {
             // count number of rows
             $this->num_rows = @pg_num_rows($this->res_result);
         }
     } else {
         $_query = @pg_query($res_conn, $this->sql_string);
         // error checking
         if (!$_query) {
             $this->errno = 1;
             $this->error = "Query failed to executed. Please check your query again. \n" . pg_last_error($res_conn);
         } else {
             // get number of affected row
             $this->affected_rows = @pg_affected_rows($_query);
             // get last OID if it is insert operation
             if (preg_match("/^(INSERT)\\s/i", $this->sql_string)) {
                 $this->insert_id = @pg_last_oid($_query);
             }
         }
         // nullify query
         $_query = null;
     }
 }
 /**
  * @see ResultSet::getRecordCount()
  */
 public function getRecordCount()
 {
     $rows = @pg_num_rows($this->result);
     if ($rows === null) {
         throw new SQLException("Error fetching num rows", pg_result_error($this->result));
     }
     return (int) $rows;
 }
function dbLastInsertId()
{
    global $database_connection;
    $result = pg_query($database_connection, "SELECT lastval();");
    if (!$result) {
        die("PG Error: " . pg_result_error($result));
    }
    $row = pg_fetch_row($result);
    return $row[0];
}
function login()
{
    $schema = "feedmati_system";
    $conn = dbconnect();
    $user = $_POST['username'];
    $loginQuery = "SELECT * FROM {$GLOBALS['schema']}.authentication WHERE user_email = \$1";
    $stmt = pg_prepare($conn, "login", $loginQuery);
    echo pg_result_error($stmt);
    if (!$stmt) {
        echo "Error, can't prepare login query<br>";
        return;
    }
    $result = pg_execute($conn, "login", array($user));
    if (pg_num_rows($result) == 0) {
        echo "Username or Password is incorrect";
        return;
    }
    $saltQuery = "SELECT salt FROM {$GLOBALS['schema']}.authentication WHERE user_email = \$1";
    $saltPrepare = pg_prepare($conn, "salt", $saltQuery);
    if (!$saltPrepare) {
        echo "Could not sanitize query for salt";
        return;
    }
    $saltResult = pg_execute($conn, "salt", array($user));
    if (pg_num_rows($saltResult) > 0) {
        $saltRow = pg_fetch_assoc($saltResult);
        $salt = $saltRow['salt'];
        $salt = trim($salt);
        $saltedpw = sha1($_POST['password'] . $salt);
    }
    $userPassPrepare = pg_prepare($conn, "pwquery", "SELECT * FROM {$GLOBALS['schema']}.authentication WHERE user_email = \$1 AND password_hash = \$2");
    if (!$userPassPrepare) {
        echo "Error, can't prepare username password query<br>";
    }
    $user = $_POST['username'];
    $pwq = array($user, $saltedpw);
    $userPassResult = pg_execute($conn, "pwquery", $pwq);
    $numrows = pg_num_rows($userPassResult);
    //if there is a match it logs the person in and adds an entry to the log
    if ($numrows == 1) {
        $action = "login";
        $_SESSION['user'] = $user;
        $userPassRow = pg_fetch_assoc($userPassResult);
        $fname = $userPassRow['fname'];
        $_SESSION['fname'] = $fname;
        header("Location: home.php");
    } else {
        echo "Username or Password is incorrect";
    }
    pg_close($conn);
}
Example #10
0
 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);
 }
Example #11
0
 /**
  * @param resource $handle PostgreSQL result resource.
  */
 public function __construct($handle)
 {
     $this->handle = $handle;
     parent::__construct(function (callable $emit) {
         $count = \pg_num_rows($this->handle);
         for ($i = 0; $i < $count; ++$i) {
             $result = \pg_fetch_assoc($this->handle);
             if (false === $result) {
                 throw new FailureException(\pg_result_error($this->handle));
             }
             yield from $emit($result);
         }
         return $i;
     });
 }
Example #12
0
function query_execute($query, $params = false)
{
    if ($params) {
        list($query_prepped, $params_array) = __query_prep_params($query, $params);
        $result = pg_query_params($query_prepped, $params_array);
    } else {
        $result = pg_query($query);
    }
    if ($result) {
        return $result;
    } else {
        error_log(pg_result_error($result));
        return false;
    }
}
Example #13
0
 /**
  * @internal
  */
 function checkError($res)
 {
     if ($res === false) {
         $in_error = true;
         $error = pg_last_error();
     } else {
         if (pg_result_status($res) == PGSQL_FATAL_ERROR) {
             $in_error = true;
             $error = pg_result_error($res);
         } else {
             $error = "";
             $in_error = false;
         }
     }
 }
Example #14
0
 function query($sql)
 {
     @pg_send_query($this->link_id, $sql);
     $this->query_result = @pg_get_result($this->link_id);
     if (pg_result_status($this->query_result) != PGSQL_FATAL_ERROR) {
         ++$this->num_queries;
         //$this->last_query_text[$this->query_result] = $sql;
         return $this->query_result;
     } else {
         if ($this->in_transaction) {
             @pg_query($this->link_id, 'ROLLBACK');
         }
         --$this->in_transaction;
         die(error(pg_result_error($this->query_result)));
         return false;
     }
 }
Example #15
0
 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);
 }
Example #16
0
 public function execute($sql)
 {
     // hide errors
     $ini_err = ini_get('display_errors');
     ini_set('display_errors', 0);
     $res = false;
     $this->res_errMsg = null;
     // --- process sql
     if ($this->dbType == 'postgres') {
         $this->res_data = pg_query($this->dbConn, $sql);
         if (!$this->res_data) {
             $this->res_errMsg = pg_last_error($this->dbConn);
         } else {
             $this->res_errMsg = pg_result_error($this->res_data);
             $this->res_affectedRows = pg_affected_rows($this->res_data);
             $this->res_rowCount = pg_num_rows($this->res_data);
             $this->res_fieldCount = pg_num_fields($this->res_data);
             $res = new dbRecordSet($this->dbType, $this->res_data, $this->res_rowCount, $this->res_fieldCount);
             // -- parse field names
             for ($i = 0; $i < $this->res_fieldCount; $i++) {
                 $this->res_fields[$i] = pg_field_name($this->res_data, $i);
                 $this->res_fieldsInfo[$i] = array();
                 $this->res_fieldsInfo[$i]['type'] = pg_field_type($this->res_data, $i);
                 $this->res_fieldsInfo[$i]['len'] = pg_field_size($this->res_data, $i);
                 $this->res_fieldsInfo[$i]['is_null'] = pg_field_is_null($this->res_data, $i);
                 $this->res_fieldsInfo[$i]['prt_len'] = pg_field_prtlen($this->res_data, $i);
             }
         }
         // log error
         if ($this->res_errMsg != '') {
             // put here code to log error
         }
     }
     // --- mysql
     if ($this->dbType == 'mysql') {
         $this->res_data = mysql_query($sql, $this->dbConn);
         if (!$this->res_data) {
             $this->res_errMsg = mysql_error($this->dbConn);
         } else {
             @($this->res_errMsg = mysql_error($this->res_data));
             @($this->res_affectedRows = mysql_affected_rows($this->res_data));
             @($this->res_rowCount = mysql_num_rows($this->res_data));
             @($this->res_fieldCount = mysql_num_fields($this->res_data));
             @($res = new dbRecordSet($this->dbType, $this->res_data, $this->res_rowCount, $this->res_fieldCount));
             // -- parse field names
             for ($i = 0; $i < $this->res_fieldCount; $i++) {
                 $this->res_fields[$i] = mysql_field_name($this->res_data, $i);
                 $this->res_fieldsInfo[$i] = array();
                 $this->res_fieldsInfo[$i]['type'] = mysql_field_type($this->res_data, $i);
                 $this->res_fieldsInfo[$i]['len'] = mysql_field_len($this->res_data, $i);
                 $this->res_fieldsInfo[$i]['flags'] = mysql_field_flags($this->res_data, $i);
             }
         }
         // log error
         if ($this->res_errMsg != '') {
             // put here code to log error
         }
     }
     $this->res_sql = $sql;
     // show debug info if on
     if ($this->debug == true) {
         print "<pre>" . $sql . "<hr>";
         if ($this->res_errMsg != '') {
             print "<span style='color: red'>" . $this->res_errMsg . "</span><hr>";
         }
         print "</pre>";
     }
     // restore errors
     ini_set('display_errors', $ini_err);
     return $res;
 }
Example #17
0
if (isset($_GET['iSortCol_0'])) {
    $sOrder = "ORDER BY ";
    for ($i = 0; $i < intval($_GET['iSortingCols']); $i++) {
        if ($_GET['bSortable_' . intval($_GET['iSortCol_' . $i])] == "true") {
            $sOrder .= $aColumns[intval($_GET['iSortCol_' . $i])] . " " . pg_escape_string($_GET['sSortDir_' . $i]) . ", ";
        }
    }
    $sOrder = substr_replace($sOrder, "", -2);
    if ($sOrder == "ORDER BY") {
        $sOrder = "";
    }
}
//------------------------------------------------------------------------------ QUERY
$query = "SELECT count(*) OVER() AS total_count,b.*,CONCAT(u.prenom,' ',u.nom) AS auteur\nFROM " . SQL_schema_app . ".bug AS b\nLEFT JOIN " . SQL_schema_app . ".utilisateur AS u ON b.id_user=u.id_user \nWHERE (statut=2 OR statut=3) " . $sWhere . " " . $sOrder . " " . $sLimit;
//echo $query;
$result = pg_query($db, $query) or die("Erreur pgSQL : " . pg_result_error($result));
if (pg_num_rows($result)) {
    $aResultTotal = pg_result($result, 0, "total_count");
} else {
    $aResultTotal = 0;
}
$iTotal = $aResultTotal;
$sOutput = '{';
$sOutput .= '"sEcho": ' . intval($_GET['sEcho']) . ', ';
$sOutput .= '"iTotalRecords": ' . $iTotal . ', ';
//	$sOutput .= '"iTotalDisplayRecords": '.$iFilteredTotal.', ';
$sOutput .= '"iTotalDisplayRecords": ' . $aResultTotal . ', ';
$sOutput .= '"aaData": [ ';
while ($row = pg_fetch_array($result, NULL, PGSQL_ASSOC)) {
    $sOutput .= "[";
    $sOutput .= '"' . $row['id_bug'] . '",';
Example #18
0
 public function execute($sql)
 {
     global $sys_dbPrefix;
     global $ses_userid;
     // hide errors
     $ini_err = ini_get('display_errors');
     ini_set('display_errors', 0);
     $res = false;
     // --- process sql
     if ($this->dbType == 'postgres') {
         $this->res_data = pg_query($this->dbConn, $sql);
         if (!$this->res_data) {
             $this->res_errMsg = pg_last_error($this->dbConn);
         } else {
             $this->res_errMsg = pg_result_error($this->res_data);
             $this->res_affectedRows = pg_affected_rows($this->res_data);
             $this->res_rowCount = pg_num_rows($this->res_data);
             $this->res_fieldCount = pg_num_fields($this->res_data);
             $res = new phpRecordSet($this->dbType, $this->res_data, $this->res_rowCount, $this->res_fieldCount);
             // -- parse field names
             for ($i = 0; $i < $this->res_fieldCount; $i++) {
                 $this->res_fields[$i] = pg_field_name($this->res_data, $i);
                 $this->res_fieldsInfo[$i] = array();
                 $this->res_fieldsInfo[$i]['type'] = pg_field_type($this->res_data, $i);
                 $this->res_fieldsInfo[$i]['len'] = pg_field_size($this->res_data, $i);
                 $this->res_fieldsInfo[$i]['is_null'] = pg_field_is_null($this->res_data, $i);
                 $this->res_fieldsInfo[$i]['prt_len'] = pg_field_prtlen($this->res_data, $i);
             }
         }
         // log error
         if ($this->res_errMsg != '') {
             $userid = $ses_userid != null ? $ses_userid : 'null';
             $ssql = "INSERT INTO " . $sys_dbPrefix . "log_error(domain, url, userid, sql, error)\n\t\t\t\t\t\t VALUES('" . $_SERVER["HTTP_HOST"] . "', '" . pg_escape_string($_SERVER["REQUEST_URI"]) . "', {$userid}, \n\t\t\t\t\t\t\t'" . pg_escape_string($sql) . "', '" . pg_escape_string($this->res_errMsg) . "');";
             pg_query($this->dbConn, $ssql);
         }
     }
     // --- mysql
     if ($this->dbType == 'mysql') {
         $this->res_data = mysql_query($sql, $this->dbConn);
         if (!$this->res_data) {
             $this->res_errMsg = mysql_error($this->dbConn);
         } else {
             $this->res_errMsg = mysql_error($this->res_data);
             $this->res_affectedRows = mysql_affected_rows($this->res_data);
             $this->res_rowCount = mysql_num_rows($this->res_data);
             $this->res_fieldCount = mysql_num_fields($this->res_data);
             $res = new phpRecordSet($this->dbType, $this->res_data, $this->res_rowCount, $this->res_fieldCount);
             // -- parse field names
             for ($i = 0; $i < $this->res_fieldCount; $i++) {
                 $this->res_fields[$i] = mysql_field_name($this->res_data, $i);
                 $this->res_fieldsInfo[$i] = array();
                 $this->res_fieldsInfo[$i]['type'] = mysql_field_type($this->res_data, $i);
                 $this->res_fieldsInfo[$i]['len'] = mysql_field_len($this->res_data, $i);
                 $this->res_fieldsInfo[$i]['flags'] = mysql_field_flags($this->res_data, $i);
             }
         }
         // log error
         if ($this->res_errMsg != '') {
             $userid = $ses_userid != null ? $ses_userid : 'null';
             $ssql = "INSERT INTO " . $sys_dbPrefix . "log_error(domain, url, userid, sql, error)\n\t\t\t\t\t\t VALUES('" . $_SERVER["HTTP_HOST"] . "', '" . mysql_escape_string($_SERVER["REQUEST_URI"]) . "', {$userid}, \n\t\t\t\t\t\t\t'" . mysql_escape_string($sql) . "', '" . mysql_escape_string($this->res_errMsg) . "');";
             mysql_query($this->dbConn, $ssql);
         }
     }
     // show debug info if on
     if ($this->debug == true) {
         print "<pre>" . $sql . "<hr>";
         if ($this->res_errMsg != '') {
             print "<span style='color: red'>" . $this->res_errMsg . "</span><hr>";
         }
         print "</pre>";
     }
     // restore errors
     ini_set('display_errors', $ini_err);
     return $res;
 }
Example #19
0
 /**
  * 数据库错误信息
  * 并显示当前的SQL语句
  * @access public
  * @return string
  */
 public function error($result = true)
 {
     $this->error = $result ? pg_result_error($this->queryID) : pg_last_error($this->_linkID);
     if ('' != $this->queryStr) {
         $this->error .= "\n [ SQL语句 ] : " . $this->queryStr;
     }
     trace($this->error, '', 'ERR');
     return $this->error;
 }
 /**
  * Get the last error message from the RecordSet.
  *
  * @return string Returns a string describing the last error that occurred in the RecordSet.
  */
 function Error()
 {
     return pg_result_error($this->result);
 }
Example #21
0
 public function getDBError()
 {
     return array('error_text' => $this->error ? $this->error : pg_result_error($this->connection), 'errno' => null);
 }
Example #22
0
    }
}
// insere funcoes no banco
if (isset($_POST[$btnInsert])) {
    // testa se já não existe uma entrada duplicada (case insensitive)
    $duplicate = false;
    for ($i = 0; $i < count($funcoes); $i++) {
        if (strcasecmp($funcoes[$i]['nome'], $_POST[$inputFuncao]) == 0) {
            $duplicate = true;
        }
    }
    // executa a inclusao
    if ($duplicate === false) {
        $result = db_query("INSERT INTO " . $sqlTabFuncao . " (nome) VALUES (" . db_quote($_POST[$inputFuncao]) . ")");
        if ($result === false) {
            $error = pg_result_error($result);
        }
        // atualiza a lista de funcoes
        $funcoes = db_select("SELECT * FROM " . $sqlTabFuncao . " " . $sqlOrdFuncao);
        header('Location: cadastro_funcao.php');
    }
}
// Modals
$inputName1 = $inputFuncao;
$inputTitle1 = "Função";
include './includes/modal_single_insert.php';
include './includes/modal_single_update.php';
// Header
$navBackUrl = "index.php";
$navOptions = "<li class=\"nav nav-btn\" data-toggle=\"modal\" data-target=\"#{$modalInsert}\"><a href=\"#\">Incluir Funcao</a></li>";
require_once './includes/header.php';
Example #23
0
 /**
  * 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();
     }
 }
 /**
  * Does a query with placeholders
  */
 function db_query($q)
 {
     $this->db_connect();
     $this->statement_handle = null;
     $this->sql = $this->db_merge($q);
     // Do the query
     $start = microtime(true);
     pg_send_query($this->db, $this->sql);
     $this->statement_handle = pg_get_result($this->db);
     $this->duration = microtime(true) - $start;
     ar_logger('SQL: [' . number_format($this->duration, 6) . '] ' . $this->sql, $this->db_connection);
     $GLOBALS['db_time'] += $this->duration;
     if ($error = pg_result_error($this->statement_handle)) {
         $errorstr = 'SQL ERROR: ' . $error . "\nSTATEMENT: " . $this->sql;
         //debug($errorstr);
         ar_logger($errorstr, $this->db_connection);
         throw_error($errorstr);
     }
     $this->sql = array();
 }
Example #25
0
 /**
  * Executes a query
  *
  * @param string $query SQL query
  * @param bool $debug False allows the query to not show in debug page
  * @author Matthew Lawrence <*****@*****.**>
  * @since 1.1.9
  * @return resource Executed query
  **/
 function query($query, $debug = true)
 {
     $this->querycount++;
     if (isset($this->get['debug']) && $debug) {
         $this->debug($query);
     }
     if (!pg_send_query($this->connection, $query)) {
         $err = pg_get_result($this->connection);
         error(QUICKSILVER_QUERY_ERROR, pg_result_error($err), $query, 0);
     } else {
         $this->last = pg_get_result($this->connection);
         if (false === $this->last) {
             error(QUICKSILVER_QUERY_ERROR, pg_result_error($err), $query, 0);
         }
     }
     return $this->last;
 }
 function ErrorMsg()
 {
     if ($this->_errorMsg !== false) {
         return $this->_errorMsg;
     }
     if (ADODB_PHPVER >= 0x4300) {
         if (!empty($this->_resultid)) {
             $this->_errorMsg = @pg_result_error($this->_resultid);
             if ($this->_errorMsg) {
                 return $this->_errorMsg;
             }
         }
         if (!empty($this->_connectionID)) {
             $this->_errorMsg = @pg_last_error($this->_connectionID);
         } else {
             $this->_errorMsg = $this->_errconnect();
         }
     } else {
         if (empty($this->_connectionID)) {
             $this->_errconnect();
         } else {
             $this->_errorMsg = @pg_errormessage($this->_connectionID);
         }
     }
     return $this->_errorMsg;
 }
Example #27
0
 /**
  * INSERT SELECT wrapper
  * $varMap must be an associative array of the form [ 'dest1' => 'source1', ... ]
  * Source items may be literals rather then field names, but strings should
  * be quoted with Database::addQuotes()
  * $conds may be "*" to copy the whole table
  * srcTable may be an array of tables.
  * @todo FIXME: Implement this a little better (seperate select/insert)?
  *
  * @param string $destTable
  * @param array|string $srcTable
  * @param array $varMap
  * @param array $conds
  * @param string $fname
  * @param array $insertOptions
  * @param array $selectOptions
  * @return bool
  */
 public function nativeInsertSelect($destTable, $srcTable, $varMap, $conds, $fname = __METHOD__, $insertOptions = [], $selectOptions = [])
 {
     $destTable = $this->tableName($destTable);
     if (!is_array($insertOptions)) {
         $insertOptions = [$insertOptions];
     }
     /*
      * If IGNORE is set, we use savepoints to emulate mysql's behavior
      * Ignore LOW PRIORITY option, since it is MySQL-specific
      */
     $savepoint = $olde = null;
     $numrowsinserted = 0;
     if (in_array('IGNORE', $insertOptions)) {
         $savepoint = new SavepointPostgres($this, 'mw', $this->queryLogger);
         $olde = error_reporting(0);
         $savepoint->savepoint();
     }
     if (!is_array($selectOptions)) {
         $selectOptions = [$selectOptions];
     }
     list($startOpts, $useIndex, $tailOpts, $ignoreIndex) = $this->makeSelectOptions($selectOptions);
     if (is_array($srcTable)) {
         $srcTable = implode(',', array_map([&$this, 'tableName'], $srcTable));
     } else {
         $srcTable = $this->tableName($srcTable);
     }
     $sql = "INSERT INTO {$destTable} (" . implode(',', array_keys($varMap)) . ')' . " SELECT {$startOpts} " . implode(',', $varMap) . " FROM {$srcTable} {$useIndex} {$ignoreIndex} ";
     if ($conds != '*') {
         $sql .= ' WHERE ' . $this->makeList($conds, LIST_AND);
     }
     $sql .= " {$tailOpts}";
     $res = (bool) $this->query($sql, $fname, $savepoint);
     if ($savepoint) {
         $bar = pg_result_error($this->mLastResult);
         if ($bar != false) {
             $savepoint->rollback();
         } else {
             $savepoint->release();
             $numrowsinserted++;
         }
         error_reporting($olde);
         $savepoint->commit();
         // Set the affected row count for the whole operation
         $this->mAffectedRows = $numrowsinserted;
         // IGNORE always returns true
         return true;
     }
     return $res;
 }
Example #28
0
 /**
  * This method is used to collect information about an error
  *
  * @param integer $error
  * @return array
  * @access public
  */
 function errorInfo($error = null)
 {
     // Fall back to MDB2_ERROR if there was no mapping.
     $error_code = MDB2_ERROR;
     $native_msg = '';
     if (is_resource($error)) {
         $native_msg = @pg_result_error($error);
     } elseif ($this->connection) {
         $native_msg = @pg_last_error($this->connection);
         if (!$native_msg && @pg_connection_status($this->connection) === PGSQL_CONNECTION_BAD) {
             $native_msg = 'Database connection has been lost.';
             $error_code = MDB2_ERROR_CONNECT_FAILED;
         }
     } else {
         $native_msg = @pg_last_error();
     }
     static $error_regexps;
     if (empty($error_regexps)) {
         $error_regexps = array('/column .* (of relation .*)?does not exist/i' => MDB2_ERROR_NOSUCHFIELD, '/(relation|sequence|table).*does not exist|class .* not found/i' => MDB2_ERROR_NOSUCHTABLE, '/database .* does not exist/' => MDB2_ERROR_NOT_FOUND, '/constraint .* does not exist/' => MDB2_ERROR_NOT_FOUND, '/index .* does not exist/' => MDB2_ERROR_NOT_FOUND, '/database .* already exists/i' => MDB2_ERROR_ALREADY_EXISTS, '/relation .* already exists/i' => MDB2_ERROR_ALREADY_EXISTS, '/(divide|division) by zero$/i' => MDB2_ERROR_DIVZERO, '/pg_atoi: error in .*: can\'t parse /i' => MDB2_ERROR_INVALID_NUMBER, '/invalid input syntax for( type)? (integer|numeric)/i' => MDB2_ERROR_INVALID_NUMBER, '/value .* is out of range for type \\w*int/i' => MDB2_ERROR_INVALID_NUMBER, '/integer out of range/i' => MDB2_ERROR_INVALID_NUMBER, '/value too long for type character/i' => MDB2_ERROR_INVALID, '/attribute .* not found|relation .* does not have attribute/i' => MDB2_ERROR_NOSUCHFIELD, '/column .* specified in USING clause does not exist in (left|right) table/i' => MDB2_ERROR_NOSUCHFIELD, '/parser: parse error at or near/i' => MDB2_ERROR_SYNTAX, '/syntax error at/' => MDB2_ERROR_SYNTAX, '/column reference .* is ambiguous/i' => MDB2_ERROR_SYNTAX, '/permission denied/' => MDB2_ERROR_ACCESS_VIOLATION, '/violates not-null constraint/' => MDB2_ERROR_CONSTRAINT_NOT_NULL, '/violates [\\w ]+ constraint/' => MDB2_ERROR_CONSTRAINT, '/referential integrity violation/' => MDB2_ERROR_CONSTRAINT, '/more expressions than target columns/i' => MDB2_ERROR_VALUE_COUNT_ON_ROW);
     }
     if (is_numeric($error) && $error < 0) {
         $error_code = $error;
     } else {
         foreach ($error_regexps as $regexp => $code) {
             if (preg_match($regexp, $native_msg)) {
                 $error_code = $code;
                 break;
             }
         }
     }
     return array($error_code, null, $native_msg);
 }
Example #29
0
 function lastError()
 {
     if ($this->mConn) {
         if ($this->mLastResult) {
             return pg_result_error($this->mLastResult);
         } else {
             return pg_last_error();
         }
     } else {
         return 'No database connection';
     }
 }
Example #30
0
<?php

//------------------------------------------------------------------------------//
//  commun/TAXON_DELETE.PHP                                                     //
//                                                                              //
//  SILENE-Flore                                                                //
//  Module extrene : Typologie des habitats naturels du PNM                     //
//                                                                              //
//  Version 1.00  28/11/12 - OlGa                                               //
//------------------------------------------------------------------------------//
//------------------------------------------------------------------------------ INIT.
include "../../_INCLUDE/config_sql.inc.php";
include "commun.inc.php";
//------------------------------------------------------------------------------ VAR.
//------------------------------------------------------------------------------ MAIN
if ($_POST['id']) {
    //------------------------------------------------------------------------------ CONNEXION SERVEUR mySQL
    $db = sql_connect(SQL_base);
    if (!$db) {
        fatal_error("Impossible de se connecter au serveur PostgreSQL.", false);
    }
    //    $db_selected=mysql_select_db(SQL_base_HABITATS,$db) or die ("Impossible d'utiliser la base : ".mysql_error());
    $id = $_POST['id'];
    $query = "DELETE FROM syntaxa.st_cortege_floristique WHERE \"idCortegeFloristique\"=" . $id . ";";
    $query .= "INSERT INTO applications.suivi (etape,id_user, tables,champ,valeur_1,valeur_2,datetime,rubrique,methode,type_modif,libelle_1,libelle_2,uid) VALUES ('2','" . $iduser . "','st_cortege_floristique','idRattachementReferentiel','" . $idrattachement . "','',NOW(),'syntaxa','manuel','suppr','" . $taxon . "','','" . $idsyntaxon . "');";
    echo $query;
    $result = pg_query($db, $query) or fatal_error("Erreur pgSQL : " . pg_result_error($result), false);
    pg_close($db);
}