コード例 #1
0
ファイル: dbutils.inc.php プロジェクト: johnpyeatt/nominatiny
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";
    }
}
コード例 #2
0
ファイル: Db.php プロジェクト: JackoThe1st/OpenRPSDev
 public function testUniqueCheck($username, $email)
 {
     //Get info from the array
     $final_username = $username;
     $final_email = $email;
     //Connect to the db
     $db = $this->connectProd();
     //Check for username and email address
     $query_user_check = "SELECT username FROM tb_users WHERE username = '******'";
     $query_email_check = "SELECT email FROM tb_users WHERE email = '" . $final_email . "'";
     pg_send_query($db, $query_user_check) or die('Query failed: ' . pg_last_error());
     $username_check_result = pg_get_result($db);
     $username_check_result_rows = pg_num_rows($username_check_result);
     pg_close($db);
     if ($username_check_result_rows == 0) {
         //Set flag if no user found
         $user_check = 'pass';
     } else {
         $user_check = 'fail';
     }
     if ($email_check_result_rows == 0) {
         //Set flag if no email is found
         $email_check = 'pass';
     } else {
         $email_check = 'fail';
     }
     if ($email_check == 'pass' && $user_check == 'pass') {
         $check_result = 'pass';
         return $check_result;
     } else {
         $check_result = 'fail';
         return $check_result;
     }
 }
コード例 #3
0
ファイル: pgsql.php プロジェクト: wenyinos/fluxbb
 function query($sql, $unbuffered = false)
 {
     if (strrpos($sql, 'LIMIT') !== false) {
         $sql = preg_replace('%LIMIT ([0-9]+),([ 0-9]+)%', 'LIMIT \\2 OFFSET \\1', $sql);
     }
     if (defined('PUN_SHOW_QUERIES')) {
         $q_start = get_microtime();
     }
     @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) {
         if (defined('PUN_SHOW_QUERIES')) {
             $this->saved_queries[] = array($sql, sprintf('%.5f', get_microtime() - $q_start));
         }
         ++$this->num_queries;
         $this->last_query_text[intval($this->query_result)] = $sql;
         return $this->query_result;
     } else {
         if (defined('PUN_SHOW_QUERIES')) {
             $this->saved_queries[] = array($sql, 0);
         }
         $this->error_no = false;
         $this->error_msg = @pg_result_error($this->query_result);
         if ($this->in_transaction) {
             @pg_query($this->link_id, 'ROLLBACK');
         }
         --$this->in_transaction;
         return false;
     }
 }
コード例 #4
0
ファイル: pgsql.php プロジェクト: mdb-webdev/punbb
 function query($sql, $unbuffered = false)
 {
     if (strlen($sql) > FORUM_DATABASE_QUERY_MAXIMUM_LENGTH) {
         exit('Insane query. Aborting.');
     }
     if (strrpos($sql, 'LIMIT') !== false) {
         $sql = preg_replace('#LIMIT ([0-9]+),([ 0-9]+)#', 'LIMIT \\2 OFFSET \\1', $sql);
     }
     if (defined('FORUM_SHOW_QUERIES') || defined('FORUM_DEBUG')) {
         $q_start = forum_microtime();
     }
     @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) {
         if (defined('FORUM_SHOW_QUERIES') || defined('FORUM_DEBUG')) {
             $this->saved_queries[] = array($sql, sprintf('%.5f', forum_microtime() - $q_start));
         }
         ++$this->num_queries;
         $this->last_query_text[$this->query_result] = $sql;
         return $this->query_result;
     } else {
         if (defined('FORUM_SHOW_QUERIES') || defined('FORUM_DEBUG')) {
             $this->saved_queries[] = array($sql, 0);
         }
         $this->error_msg = @pg_result_error($this->query_result);
         if ($this->in_transaction) {
             @pg_query($this->link_id, 'ROLLBACK');
         }
         --$this->in_transaction;
         return false;
     }
 }
コード例 #5
0
ファイル: postgresql.php プロジェクト: brunopagno/everydayvis
 function pg_db_send_query($iConn, $sQry)
 {
     $iQuery = @pg_send_query($iConn, $sQry);
     if (!$iQuery) {
         $erro = pg_ErrorMessage($iConn) . "\n" . $sQry;
         msgErro($erro);
     }
     return $iQuery;
 }
コード例 #6
0
 function executeQuery($sql_commands)
 {
     if (!pg_send_query($this->link, $sql_commands)) {
         throw new DatabaseException("PostgreSQL database query failed on following query:\n{$sql_commands}");
     }
     $this->res = pg_get_result($this->link);
     DEBUG("DB: Query was: <em>{$sql_commands}</em>");
     $this->executedQueries++;
     return true;
 }
コード例 #7
0
ファイル: Connection.php プロジェクト: amphp/pgsql
 /**
  * Dispatch an unprepared query asynchronously
  *
  * @param string $query
  * @return \Amp\Promise
  */
 public function query(string $query) : \Amp\Promise
 {
     if ($this->queryCacheSize > $this->maxOutstandingQueries) {
         return new \Amp\Failure(new \RuntimeException("Too busy"));
     }
     $deferred = new \Amp\Deferred();
     $this->queryCache[] = [self::$OP_QUERY, [$query], $deferred];
     $this->queryCacheSize++;
     if (!$this->queryCacheSize++) {
         $sendResult = \pg_send_query($this->db, $query);
         $this->processSendResult($sendResult);
     }
     return $deferred->promise();
 }
コード例 #8
0
ファイル: Db.php プロジェクト: aoyagikouhei/pg
 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);
 }
コード例 #9
0
ファイル: pgsql.inc.php プロジェクト: OvBB/v1.0
 function query($strSQL)
 {
     global $aQueries;
     // Save the query.
     $aQueries[] = $strSQL;
     // Execute the query.
     $querySuccess = pg_send_query($this->objConnection, $strSQL);
     $this->objResult = @pg_get_result($this->objConnection);
     // Return the result.
     if ($querySuccess === FALSE) {
         DatabaseError();
     } else {
         return TRUE;
     }
 }
コード例 #10
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;
     }
 }
コード例 #11
0
ファイル: Database_Postgresql.php プロジェクト: anqqa/Anqh
 public function query_execute($sql)
 {
     // Make sure the database is connected
     $this->connect();
     if ($result = pg_send_query($this->connection, $sql)) {
         $result = pg_get_result($this->connection);
     }
     if (!is_resource($result)) {
         throw new Database_Exception(':error [ :query ]', array(':error' => pg_last_error($this->connection), ':query' => $sql));
     }
     // Set the last query
     $this->last_query = $sql;
     if ($this->config['fix_booleans']) {
         return Database_Postgresql_Result_Boolean::factory($result, $sql, $this->connection, $this->config['object']);
     }
     return new Database_Postgresql_Result($result, $sql, $this->connection, $this->config['object']);
 }
コード例 #12
0
ファイル: PgsqlDriver.php プロジェクト: jasir/dbal
 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);
 }
コード例 #13
0
ファイル: loader.php プロジェクト: Exsul/inyo
function SQLLoad($file)
{
    header("SQL: {$file}", false);
    $con = db::RawConnection();
    $sql = file_get_contents($file);
    pg_send_query($con, $sql);
    if (($error = pg_last_error($con)) !== '') {
        die("Failure at loading {{$file}} with {{$error}}");
    }
    while (pg_connection_busy($con)) {
        sleep(1);
    }
    while (pg_get_result($con) !== false) {
        if (($error = pg_last_error($con)) !== '') {
            die("Failure at loading {{$file}} with {{$error}}");
        }
    }
}
コード例 #14
0
 /**
  * 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();
 }
コード例 #15
0
 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;
                 }
             }
         }
     }
 }
コード例 #16
0
 public function transferDBtoArray($host, $user, $password, $db_or_dsn_name, $cndriver = "mysql")
 {
     $this->m = 0;
     if (!$this->connect($host, $user, $password, $db_or_dsn_name, $cndriver)) {
         echo "Fail to connect database";
         exit(0);
     }
     if ($this->debugsql == true) {
         echo "<textarea cols='100' rows='40'>{$this->sql}</textarea>";
         die;
     }
     if ($cndriver == "odbc") {
         $result = odbc_exec($this->myconn, $this->sql);
         while ($row = odbc_fetch_array($result)) {
             foreach ($this->arrayfield as $out) {
                 $this->arraysqltable[$this->m]["{$out}"] = $row["{$out}"];
             }
             $this->m++;
         }
     } elseif ($cndriver == "psql") {
         pg_send_query($this->myconn, $this->sql);
         $result = pg_get_result($this->myconn);
         while ($row = pg_fetch_array($result, NULL, PGSQL_ASSOC)) {
             foreach ($this->arrayfield as $out) {
                 $this->arraysqltable[$this->m]["{$out}"] = $row["{$out}"];
             }
             $this->m++;
         }
     } else {
         @mysql_query("set names 'utf8'");
         $result = @mysql_query($this->sql);
         //query from db
         while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
             foreach ($this->arrayfield as $out) {
                 $this->arraysqltable[$this->m]["{$out}"] = $row["{$out}"];
             }
             $this->m++;
         }
     }
     // print_r(   $this->arraysqltable);die;
     //close connection to db
 }
コード例 #17
0
        $query .= $response->attributes()->shef_id;
        $query .= "',";
        $query .= $response->attributes()->elev;
        $query .= ",";
        $query .= $response->attributes()->lat;
        $query .= ",";
        $query .= $response->attributes()->lon;
        $query .= ",'";
        $query .= $response->attributes()->ObTime;
        $query .= "','";
        $query .= $response->attributes()->provider;
        $query .= "',";
        $query .= $response->attributes()->data_value;
        $query .= ",'";
        $query .= $response->attributes()->QCD;
        $query .= "','";
        $query .= $response->attributes()->QCA;
        $query .= "','";
        $query .= $response->attributes()->QCR;
        $query .= "')";
        $pgresult = pg_send_query($dbhandle, $query);
        $res1 = pg_get_result($dbhandle);
    }
    echo '  ...UDFCD 24 HourPrecip done! ' . $counter2 . ' records inserted. ' . date("F j, Y, g:i:s a") . '<br />';
}
//call post processing code:
echo '<br />Calling pg function data_processing.madis_daily_process()' . date("F j, Y, g:i:s a") . '<br />';
$query = 'SELECT * FROM data_processing.madis_daily_process()';
$pgresult = pg_send_query($dbhandle, $query);
$res1 = pg_get_result($dbhandle);
echo '<br />Processing ended at ' . date("F j, Y, g:i:s a") . '. ' . $counter1 . ' total records inserted.';
コード例 #18
0
ファイル: pgsql.php プロジェクト: BackupTheBerlios/qsf-svn
 /**
  * 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;
 }
コード例 #19
0
 public function doQuery($sql)
 {
     if (function_exists('mb_convert_encoding')) {
         $sql = mb_convert_encoding($sql, 'UTF-8');
     }
     $this->mTransactionState->check();
     if (pg_send_query($this->mConn, $sql) === false) {
         throw new DBUnexpectedError($this, "Unable to post new query to PostgreSQL\n");
     }
     $this->mLastResult = pg_get_result($this->mConn);
     $this->mTransactionState->check();
     $this->mAffectedRows = null;
     if (pg_result_error($this->mLastResult)) {
         return false;
     }
     return $this->mLastResult;
 }
コード例 #20
0
ファイル: db_pgsql.php プロジェクト: mainhan1804/xomvanphong
 /**
  * Query the database.
  *
  * @param string $string The query SQL.
  * @param boolean|int $hide_errors 1 if hide errors, 0 if not.
  * @param integer $write_query 1 if executes on slave database, 0 if not.
  * @return resource The query data.
  */
 function query($string, $hide_errors = 0, $write_query = 0)
 {
     global $mybb;
     $string = preg_replace("#LIMIT (\\s*)([0-9]+),(\\s*)([0-9]+)\$#im", "LIMIT \$4 OFFSET \$2", trim($string));
     $this->last_query = $string;
     get_execution_time();
     if (strtolower(substr(ltrim($string), 0, 5)) == 'alter') {
         $string = preg_replace("#\\sAFTER\\s([a-z_]+?)(;*?)\$#i", "", $string);
         if (strstr($string, 'CHANGE') !== false) {
             $string = str_replace(' CHANGE ', ' ALTER ', $string);
         }
     }
     if ($write_query && $this->write_link) {
         while (pg_connection_busy($this->write_link)) {
         }
         $this->current_link =& $this->write_link;
         pg_send_query($this->current_link, $string);
         $query = pg_get_result($this->current_link);
     } else {
         while (pg_connection_busy($this->read_link)) {
         }
         $this->current_link =& $this->read_link;
         pg_send_query($this->current_link, $string);
         $query = pg_get_result($this->current_link);
     }
     if (pg_result_error($query) && !$hide_errors) {
         $this->error($string, $query);
         exit;
     }
     $query_time = get_execution_time();
     $this->query_time += $query_time;
     $this->query_count++;
     $this->last_result = $query;
     if ($mybb->debug_mode) {
         $this->explain_query($string, $query_time);
     }
     return $query;
 }
コード例 #21
0
<?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');
    }
コード例 #22
0
ファイル: setup.php プロジェクト: netconstructor/Nominatim
 }
 foreach (glob(CONST_BasePath . '/data/tiger2011/*.sql') as $sFile) {
     echo $sFile . ': ';
     $hFile = fopen($sFile, "r");
     $sSQL = fgets($hFile, 100000);
     $iLines = 0;
     while (true) {
         for ($i = 0; $i < $iInstances; $i++) {
             if (!pg_connection_busy($aDBInstances[$i]->connection)) {
                 while (pg_get_result($aDBInstances[$i]->connection)) {
                 }
                 $sSQL = fgets($hFile, 100000);
                 if (!$sSQL) {
                     break 2;
                 }
                 if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) {
                     fail(pg_last_error($oDB->connection));
                 }
                 $iLines++;
                 if ($iLines == 1000) {
                     echo ".";
                     $iLines = 0;
                 }
             }
         }
         usleep(10);
     }
     fclose($hFile);
     $bAnyBusy = true;
     while ($bAnyBusy) {
         $bAnyBusy = false;
コード例 #23
0
ファイル: Extpgsql.01.php プロジェクト: exakat/exakat
<?php

$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
if (!pg_connection_busy($dbconn)) {
    pg_send_query($dbconn, "select * from authors; select count(*) from authors;");
}
$res1 = pg_get_result($dbconn);
echo "First call to pg_get_result(): {$res1}\n";
$rows1 = pg_num_rows($res1);
echo "{$res1} has {$rows1} records\n\n";
$res2 = pg_get_result($dbconn);
echo "Second call to pg_get_result(): {$res2}\n";
$rows2 = pg_num_rows($res2);
echo "{$res2} has {$rows2} records\n";
コード例 #24
0
ファイル: PhorumPostgresqlDB.php プロジェクト: samuell/Core
 /**
  * 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);
 }
コード例 #25
0
ファイル: Connection.php プロジェクト: un0topface/Connection
 /**
  * Send query with/without template
  * @param string $query query string or template
  * @param array|null $data query parameters
  */
 private function sendQuery($query, array $data = null)
 {
     if (!is_null($data)) {
         $Template = new QueryTemplate();
         $Template->load($query);
         pg_send_query($this->Resource, $Template->parse($data));
     } else {
         pg_send_query($this->Resource, $query);
     }
 }
コード例 #26
0
ファイル: Connection.php プロジェクト: SebLours/Foundation
 /**
  * executeAnonymousQuery
  *
  * Performs a raw SQL query
  *
  * @access public
  * @param  string              $sql The sql statement to execute.
  * @return ResultHandler|array
  */
 public function executeAnonymousQuery($sql)
 {
     $ret = pg_send_query($this->getHandler(), $sql);
     return $this->testQuery($ret, sprintf("Anonymous query failed '%s'.", $sql))->getQueryResult($sql);
 }
コード例 #27
0
 /**
  * @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;
 }
コード例 #28
0
 public function transferDBtoArray($host, $user, $password, $db_or_dsn_name, $cndriver = "mysql")
 {
     $this->m = 0;
     if (!$this->connect($host, $user, $password, $db_or_dsn_name, $cndriver)) {
         echo "Fail to connect database";
         exit(0);
     }
     if ($this->debugsql == true) {
         echo "<textarea cols='100' rows='40'>{$this->sql}</textarea>";
         die;
     }
     if ($cndriver == "odbc") {
         $result = odbc_exec($this->myconn, $this->sql);
         while ($row = odbc_fetch_array($result)) {
             foreach ($this->arrayfield as $out) {
                 $this->arraysqltable[$this->m]["{$out}"] = $row["{$out}"];
             }
             $this->m++;
         }
     } elseif ($cndriver == "psql") {
         pg_send_query($this->myconn, $this->sql);
         $result = pg_get_result($this->myconn);
         while ($row = pg_fetch_array($result, NULL, PGSQL_ASSOC)) {
             foreach ($this->arrayfield as $out) {
                 $this->arraysqltable[$this->m]["{$out}"] = $row["{$out}"];
             }
             $this->m++;
         }
     } else {
         @mysql_query("set names 'utf8'");
         //$this->pageBandsInfo
         $result = @mysql_query($this->sql);
         //query from db
         while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
             foreach ($this->arrayfield as $out) {
                 $this->arraysqltable[$this->m]["{$out}"] = $row["{$out}"];
             }
             $this->m++;
         }
         $this->pageBandsInfo['totalDetail'] = count($this->arraysqltable);
         $this->pageBandsInfo['totalDetailHeight'] = $this->pageBandsInfo['totalDetail'] * $this->pageBandsInfo['detailHeight'];
         if (!empty($this->pageBandsInfo['groupName']) && !empty($this->arraysqltable[0])) {
             foreach ($this->arraysqltable[0] as $nameField => $value) {
                 if (trim(strtolower($this->pageBandsInfo['groupName'])) == trim(strtolower($nameField))) {
                     $this->pageBandsInfo['groupName'] = $nameField;
                 }
             }
         }
         if (!empty($this->pageBandsInfo['groupName'])) {
             foreach ($this->arraysqltable as $key => $r) {
                 $chave = $r[$this->pageBandsInfo['groupName']];
                 $arrayGoup[$chave][] = $r;
             }
             $this->pageBandsInfo['totalGroup'] = count($arrayGoup);
             $this->pageBandsInfo['totalGroupHheight'] = $this->pageBandsInfo['totalGroup'] * $this->pageBandsInfo['groupHeight'];
         }
     }
     //print_r(   $this->arraysqltable);die;
     //close connection to db
 }
コード例 #29
0
 public function doQuery($sql)
 {
     if (function_exists('mb_convert_encoding')) {
         $sql = mb_convert_encoding($sql, 'UTF-8');
     }
     // Clear previously left over PQresult
     while ($res = pg_get_result($this->mConn)) {
         pg_free_result($res);
     }
     if (pg_send_query($this->mConn, $sql) === false) {
         throw new DBUnexpectedError($this, "Unable to post new query to PostgreSQL\n");
     }
     $this->mLastResult = pg_get_result($this->mConn);
     $this->mAffectedRows = null;
     if (pg_result_error($this->mLastResult)) {
         return false;
     }
     return $this->mLastResult;
 }
コード例 #30
0
 public function transferDBtoArray($host, $user, $password, $db_or_dsn_name, $cndriver = "mysql")
 {
     $this->m = 0;
     if (!$this->connect($host, $user, $password, $db_or_dsn_name, $cndriver)) {
         echo "Fail to connect database";
         exit(0);
     }
     if ($this->debugsql == true) {
         echo $this->sql;
         die;
     }
     if ($cndriver == "odbc") {
         $result = odbc_exec($this->myconn, $this->sql);
         while ($row = odbc_fetch_array($result)) {
             foreach ($this->arrayfield as $out) {
                 $this->arraysqltable[$this->m]["{$out}"] = $row["{$out}"];
             }
             $this->m++;
         }
     } elseif ($cndriver == "psql") {
         pg_send_query($this->myconn, $this->sql);
         $result = pg_get_result($this->myconn);
         while ($row = pg_fetch_array($result, NULL, PGSQL_ASSOC)) {
             foreach ($this->arrayfield as $out) {
                 $this->arraysqltable[$this->m]["{$out}"] = $row["{$out}"];
             }
             $this->m++;
         }
     } else {
         $result = @mysql_query($this->sql);
         //query from db
         while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
             foreach ($this->arrayfield as $out) {
                 $this->arraysqltable[$this->m]["{$out}"] = $row["{$out}"];
             }
             $this->m++;
         }
     }
     $this->disconnect($cndriver);
     //close connection to db
     if (isset($this->arrayVariable)) {
         $this->variable_calculation($m);
     }
 }