/**
  * 连接数据库方法
  * @access public
  */
 public function connect($config = '', $linkNum = 0)
 {
     if (!isset($this->linkID[$linkNum])) {
         if (empty($config)) {
             $config = $this->config;
         }
         $pconnect = !empty($config['params']['persist']) ? $config['params']['persist'] : $this->pconnect;
         $conn = $pconnect ? 'pg_pconnect' : 'pg_connect';
         $this->linkID[$linkNum] = $conn('host=' . $config['hostname'] . ' port=' . $config['hostport'] . ' dbname=' . $config['database'] . ' user='******'username'] . '  password='******'password']);
         if (0 !== pg_connection_status($this->linkID[$linkNum])) {
             E($this->error(false));
         }
         //设置编码
         pg_set_client_encoding($this->linkID[$linkNum], $config['charset']);
         //$pgInfo = pg_version($this->linkID[$linkNum]);
         //$dbVersion = $pgInfo['server'];
         // 标记连接成功
         $this->connected = true;
         //注销数据库安全信息
         if (1 != C('DB_DEPLOY_TYPE')) {
             unset($this->config);
         }
     }
     return $this->linkID[$linkNum];
 }
Exemple #2
0
 /**
  * Connect to database
  *
  * @param array $options
  * @return array
  */
 public function connect($options)
 {
     $result = ['version' => null, 'status' => 0, 'error' => [], 'errno' => 0, 'success' => false];
     // we could pass an array or connection string right a way
     if (is_array($options)) {
         $str = 'host=' . $options['host'] . ' port=' . $options['port'] . ' dbname=' . $options['dbname'] . ' user='******'username'] . ' password='******'password'];
     } else {
         $str = $options;
     }
     $connection = pg_connect($str);
     if ($connection !== false) {
         $this->db_resource = $connection;
         $this->connect_options = $options;
         $this->commit_status = 0;
         pg_set_error_verbosity($connection, PGSQL_ERRORS_VERBOSE);
         pg_set_client_encoding($connection, 'UNICODE');
         $result['version'] = pg_version($connection);
         $result['status'] = pg_connection_status($connection) === PGSQL_CONNECTION_OK ? 1 : 0;
         $result['success'] = true;
     } else {
         $result['error'][] = 'db::connect() : Could not connect to database server!';
         $result['errno'] = 1;
     }
     return $result;
 }
Exemple #3
0
 /**
  * Establish a new connection to postgreSQL server.
  *
  * @return string | boolean postgreSQL persistent link identifier on success, or FALSE on failure.
  */
 private function establishConnection()
 {
     $function = $this->config['persistent'] ? 'pg_pconnect' : 'pg_connect';
     $connection = $function('host=' . $this->config['host'] . ' port=' . $this->config['port'] . ' dbname=' . $this->config['database'] . ' user='******'user'] . ' password='******'password'], false);
     pg_set_client_encoding($connection, $this->config['charset']);
     return $connection;
 }
 function connect()
 {
     global $php_errormsg;
     $persistent = isset($this->config['persistent']) ? $this->config['persistent'] : null;
     $connstr = '';
     if ($host = $this->config['host']) {
         $connstr = 'host=' . $host;
     }
     if ($port = $this->config['port']) {
         $connstr .= ' port=' . $port;
     }
     if ($database = $this->config['database']) {
         $connstr .= ' dbname=\'' . addslashes($database) . '\'';
     }
     if ($user = $this->config['user']) {
         $connstr .= ' user=\'' . addslashes($user) . '\'';
     }
     if ($password = $this->config['password']) {
         $connstr .= ' password=\'' . addslashes($password) . '\'';
     }
     if ($persistent) {
         $conn = @pg_pconnect($connstr);
     } else {
         $conn = @pg_connect($connstr);
     }
     if (!is_resource($conn)) {
         $this->_raiseError($php_errormsg);
     }
     if (isset($this->config['charset']) && ($charset = $this->config['charset'])) {
         pg_set_client_encoding($conn, $charset);
     }
     $this->connectionId = $conn;
 }
Exemple #5
0
 public function connect($config = [])
 {
     $this->config = $config;
     $dsn = 'host=' . $this->config['host'] . ' ';
     if (!empty($this->config['port'])) {
         $dsn .= 'port=' . $this->config['port'] . ' ';
     }
     if (!empty($this->config['database'])) {
         $dsn .= 'dbname=' . $this->config['database'] . ' ';
     }
     if (!empty($this->config['user'])) {
         $dsn .= 'user='******'user'] . ' ';
     }
     if (!empty($this->config['password'])) {
         $dsn .= 'password='******'password'] . ' ';
     }
     if (!empty($this->config['dsn'])) {
         $dsn = $this->config['dsn'];
     }
     $dsn = rtrim($dsn);
     $this->connect = $this->config['pconnect'] === true ? @pg_pconnect($dsn) : @pg_connect($dsn);
     if (empty($this->connect)) {
         die(getErrorMessage('Database', 'connectError'));
     }
     if (!empty($this->config['charset'])) {
         pg_set_client_encoding($this->connect, $this->config['charset']);
     }
 }
 /**
  * Set client encoding
  * @param string $encoding
  * @return int 0 on success or -1 on error
  */
 function set_client_encoding($encoding = "")
 {
     if ($encoding != "") {
         return pg_set_client_encoding($this->connection, $encoding);
     }
     return 0;
 }
 function init()
 {
     $this->query("set client_encoding = 'UTF-8'");
     pg_set_client_encoding("UNICODE");
     $this->query("set datestyle = 'ISO, european'");
     $this->query("set TIME ZONE 0");
     return true;
 }
function connect_db()
{
    if ($conn = pg_connect("host=" . SQL_HOST . " port=" . SQL_PORT . " dbname=" . SQL_DATABASE . " user="******" password=" . SQL_PASSWORD)) {
        pg_set_client_encoding($conn, 'UNICODE');
        return $conn;
    } else {
        return false;
    }
}
Exemple #9
0
 function WikiDB_backend_PearDB($dbparams)
 {
     // Find and include PEAR's DB.php. maybe we should force our private version again...
     // if DB would have exported its version number, it would be easier.
     @(require_once 'DB/common.php');
     // Either our local pear copy or the system one
     // check the version!
     $name = check_php_version(5) ? "escapeSimple" : strtolower("escapeSimple");
     // TODO: apparently some Pear::Db version adds LIMIT 1,0 to getOne(),
     // which is invalid for "select version()"
     if (!in_array($name, get_class_methods("DB_common"))) {
         $finder = new FileFinder();
         $dir = dirname(__FILE__) . "/../../pear";
         $finder->_prepend_to_include_path($dir);
         include_once "{$dir}/DB/common.php";
         // use our version instead.
         if (!in_array($name, get_class_methods("DB_common"))) {
             $pearFinder = new PearFileFinder("lib/pear");
             $pearFinder->includeOnce('DB.php');
         } else {
             include_once "{$dir}/DB.php";
         }
     } else {
         include_once "DB.php";
     }
     // Install filter to handle bogus error notices from buggy DB.php's.
     // TODO: check the Pear_DB version, but how?
     if (0) {
         global $ErrorManager;
         $ErrorManager->pushErrorHandler(new WikiMethodCb($this, '_pear_notice_filter'));
         $this->_pearerrhandler = true;
     }
     // Open connection to database
     $this->_dsn = $dbparams['dsn'];
     $this->_dbparams = $dbparams;
     $this->_lock_count = 0;
     // persistent is usually a DSN option: we override it with a config value.
     //   phptype://username:password@hostspec/database?persistent=false
     $dboptions = array('persistent' => DATABASE_PERSISTENT, 'debug' => 2);
     //if (preg_match('/^pgsql/', $this->_dsn)) $dboptions['persistent'] = false;
     $this->_dbh = DB::connect($this->_dsn, $dboptions);
     $dbh =& $this->_dbh;
     if (DB::isError($dbh)) {
         trigger_error(sprintf("Can't connect to database: %s", $this->_pear_error_message($dbh)), E_USER_ERROR);
     }
     $dbh->setErrorHandling(PEAR_ERROR_CALLBACK, array($this, '_pear_error_callback'));
     $dbh->setFetchMode(DB_FETCHMODE_ASSOC);
     $prefix = isset($dbparams['prefix']) ? $dbparams['prefix'] : '';
     $this->_table_names = array('page_tbl' => $prefix . 'page', 'version_tbl' => $prefix . 'version', 'link_tbl' => $prefix . 'link', 'recent_tbl' => $prefix . 'recent', 'nonempty_tbl' => $prefix . 'nonempty');
     $page_tbl = $this->_table_names['page_tbl'];
     $version_tbl = $this->_table_names['version_tbl'];
     $p = strlen(PAGE_PREFIX) + 1;
     $this->page_tbl_fields = "{$page_tbl}.id AS id, substring({$page_tbl}.pagename from {$p}) AS pagename, {$page_tbl}.hits AS hits";
     $this->version_tbl_fields = "{$version_tbl}.version AS version, {$version_tbl}.mtime AS mtime, " . "{$version_tbl}.minor_edit AS minor_edit, {$version_tbl}.content AS content, {$version_tbl}.versiondata AS versiondata";
     $this->_expressions = array('maxmajor' => "MAX(CASE WHEN minor_edit=0 THEN version END)", 'maxminor' => "MAX(CASE WHEN minor_edit<>0 THEN version END)", 'maxversion' => "MAX(version)", 'notempty' => "<>''", 'iscontent' => "content<>''");
     pg_set_client_encoding("iso-8859-1");
 }
Exemple #10
0
 function WikiDB_backend_PearDB_ffpgsql($dbparams)
 {
     $dbparams['dsn'] = str_replace('ffpgsql:', 'pgsql:', $dbparams['dsn']);
     parent::WikiDB_backend_PearDB_pgsql($dbparams);
     $p = strlen(PAGE_PREFIX) + 1;
     $page_tbl = $this->_table_names['page_tbl'];
     $this->page_tbl_fields = "{$page_tbl}.id AS id, substring({$page_tbl}.pagename from {$p}) AS pagename, {$page_tbl}.hits AS hits";
     pg_set_client_encoding("iso-8859-1");
 }
function deleteLocal()
{
    include '../conf/config.php';
    // connection to database goes here
    $dbconn = pg_connect("host={$host} port={$port} dbname={$db_name} user={$username} password={$password}") or die('Could not connect: ' . pg_last_error());
    pg_set_client_encoding($dbconn, "utf-8");
    $actualiza = "DELETE FROM locais  WHERE id = " . $_POST["idlocal"] . ";  ";
    pg_query($actualiza) or die('Could not insert: ' . pg_last_error());
    pg_close($dbconn);
}
 public function connect()
 {
     $this->conn = pg_connect($this->connString);
     if ($this->conn === FALSE) {
         throw new DBException("Failed to connect to {$this->connString}");
     }
     if (pg_set_client_encoding($this->conn, "UTF-8") != 0) {
         throw new DBException("Failed to set UTF-8 client encoding: " . pg_last_error($this->conn));
     }
 }
Exemple #13
0
 /**
  * A method to set the client charset
  *
  * @param string $charset
  * @return mixed True on success, PEAR_Error otherwise
  */
 function setClientCharset($charset)
 {
     if (!empty($charset) && $this->oDbh) {
         $pg = $this->oDbh->getConnection();
         if (@pg_set_client_encoding($pg, $charset) == -1) {
             return new PEAR_Error(pg_errormessage($pg));
         }
     }
     return true;
 }
function updateLocal()
{
    include '../conf/config.php';
    // connection to database goes here
    $dbconn = pg_connect("host={$host} port={$port} dbname={$db_name} user={$username} password={$password}") or die('Could not connect: ' . pg_last_error());
    pg_set_client_encoding($dbconn, "utf-8");
    $actualiza = "UPDATE locais SET \n\t\t\t\t\t\tnomecomercial='" . $_POST["nome"] . "', \n\t\t\t\t\t\tactividade_id='" . $_POST["actividade_id"] . "',\n\n\t\t\t\t\t\trexime='" . $_POST["rexime"] . "',\n\t\t\t\t\t\tapertura='" . $_POST["apertura"] . "',\n\t\t\t\t\t\tm2='" . $_POST["superficie"] . "',\n\t\t\t\t\t\tnomexerente='" . $_POST["xerente"] . "',\n\n\t\t\t\t\t\tzone_id='" . $_POST["zone_id"] . "',\n\t\t\t\t\t\t\n\t\t\t\t\t\tvia_id='" . $_POST["viaId"] . "',\n\t\t\t\t\t\trua='" . $_POST["rua"] . "',\n\t\t\t\t\t\tnum='" . $_POST["num"] . "',\n\t\t\t\t\t\tcp='" . $_POST["cp"] . "',\n\t\t\t\t\t\tlat='" . $_POST["lat"] . "',\n\t\t\t\t\t\tlon='" . $_POST["lon"] . "',\n\n\t\t\t\t\t\tweb='" . $_POST["web"] . "',\n\t\t\t\t\t\trs_facebook='" . $_POST["rs_facebook"] . "',\n\t\t\t\t\t\trs_twitter='" . $_POST["rs_twitter"] . "',\n\t\t\t\t\t\trs_pinterest='" . $_POST["rs_pinterest"] . "',\n\t\t\t\t\t\trs_youtube='" . $_POST["rs_youtube"] . "',\n\t\t\t\t\t\trs_instagram='" . $_POST["rs_instagram"] . "',\n\n\t\t\t\t\t\temail='" . $_POST["email"] . "',\n\t\t\t\t\t\ttelefono='" . $_POST["tlf"] . "',\n\t\t\t\t\t\tmobil='" . $_POST["mobil"] . "',\n\t\t\t\t\t\tfax='" . $_POST["fax"] . "'\n\t\t\t\t\t\t\n\n\t\t\t\t\tWHERE id = " . $_POST["idlocal"] . ";  ";
    pg_query($actualiza) or die('Could not insert: ' . pg_last_error());
    pg_close($dbconn);
}
 function pgBackupRestore($uiHost, $uiUser, $uiPassword, $uiDatabase, $uiPort = 5432)
 {
     $this->Link_ID = pg_pconnect("host={$uiHost} port={$uiPort} dbname={$uiDatabase} user={$uiUser} password={$uiPassword}");
     if (!$this->Link_ID) {
         $this->Error("Can't connect to the Postgres Database", true);
     }
     $this->Database = $uiDatabase;
     $this->Connected = $this->Link_ID ? true : false;
     pg_set_client_encoding($this->Link_ID, $this->Encoding);
 }
 /**
  * Método que irá abrir uma conexão com servidor.
  * 
  * @param <string> $name >> nome da conexão.
  */
 static function connection($name)
 {
     $config = Connection::get($name);
     # iniciando conexão, caso isto ainda não tenha sido feito.
     if (!array_key_exists('connection', $config)) {
         Connection::$connections[$name]['connection'] = pg_connect("host={$config['host']} port={$config['port']} dbname={$config['database']} user={$config['user']} password={$config['password']}");
         pg_set_client_encoding(Connection::$connections[$name]['connection'], 'UTF-8');
     }
     return Connection::$connections[$name]['connection'];
 }
Exemple #17
0
 public function connect()
 {
     if ($connection = pg_connect("host={$this->host} port={$this->port} dbname={$this->name} user={$this->user} password={$this->pass}")) {
         pg_set_client_encoding($connection, $this->charset);
         $this->connection = $connection;
     } else {
         trigger_error('Could not connect to Database');
         exit;
     }
 }
Exemple #18
0
 /**
 	Initialises a new pgsql database.
 
 	This database driver accepts the same parameters as the ones allowed in the connection string
 	passed to pg_connect plus "encoding", which is the encoding used by the client as specified
 	by pg_set_client_encoding.
 
 	The default encoding is UNICODE.
 
 	@param	$aParams	The parameters of the database.
 	@see	http://php.net/pg_connect
 	@see	http://php.net/pg_set_client_encoding
 */
 public function __construct($aParams = array())
 {
     function_exists('pg_connect') or burn('ConfigurationException', sprintf(_WT('The "%s" PHP extension is required by this database driver.'), 'PostgreSQL'));
     $sEncoding = array_value($aParams, 'encoding', 'UNICODE');
     unset($aParams['encoding']);
     $sConnection = null;
     foreach ($aParams as $sKey => $sValue) {
         $sConnection .= $sKey . "='" . str_replace(array("'", "\\"), array("\\'", "\\\\"), $sValue) . "' ";
     }
     // pg_connect triggers a warning if the connection failed.
     $this->rLink = @pg_connect($sConnection, PGSQL_CONNECT_FORCE_NEW);
     $this->rLink === false and burn('DatabaseException', sprintf(_WT("Failed to connect to the database with the following error:\n%s"), array_value(error_get_last(), 'message')));
     pg_set_client_encoding($this->rLink, $sEncoding) != -1 or burn('InvalidArgumentException', sprintf(_WT('Encoding "%s" is invalid.'), $sEncoding));
 }
function my_PGSQL_db_connect()
{
    // http://www.php.net/manual/ru/ref.pgsql.php
    $dblocation = "localhost";
    $dbuser = "******";
    $dbpassword = "";
    $dbname = "bacula";
    /*$db = pg_connect("host='$dblocation' dbname='$dbname' user='******' password='******'")
      or die("[PGSQL]" . pg_last_error());*/
    $db = pg_connect("host='{$dblocation}' dbname='{$dbname}' user='******' password='******'") or die("[PGSQL]" . pg_last_error());
    pg_set_client_encoding($db, 'SQL_ASCII');
    echo "Connect [PGSQL] ", $dbname, ". Encoding ", pg_client_encoding(), ".  OK.\n";
    return $db;
}
Exemple #20
0
 public function connect(array $params)
 {
     $host = $params["host"];
     $user = $params["user"];
     $pass = $params["password"];
     $dbs = $params["database"];
     $host = isset($params["port"]) ? $host . " port=" . $params["port"] : $host;
     $conn = pg_connect("host={$host} dbname={$dbs} user={$user} password={$pass}", PGSQL_CONNECT_FORCE_NEW);
     if ($conn) {
         if (isset($params["charset"])) {
             pg_set_client_encoding($conn, $params["charset"]);
         }
         return $conn;
     } else {
         return "cannot connect to PostgreSQL. please check your configuration.";
     }
 }
Exemple #21
0
 /**
  * 连接数据库方法
  * @access public
  */
 public function connect($config = '', $linkNum = 0)
 {
     if (!isset($this->linkID[$linkNum])) {
         if (empty($config)) {
             $config = $this->config;
         }
         $pconnect = !empty($config['params']['persist']) ? $config['params']['persist'] : $this->pconnect;
         $conn = $pconnect ? 'pg_pconnect' : 'pg_connect';
         $this->linkID[$linkNum] = $conn('host=' . $config['hostname'] . ' port=' . $config['hostport'] . ' dbname=' . $config['database'] . ' user='******'username'] . '  password='******'password']);
         if (0 !== pg_connection_status($this->linkID[$linkNum])) {
             E($this->error(false));
         }
         //设置编码
         pg_set_client_encoding($this->linkID[$linkNum], $config['charset']);
     }
     return $this->linkID[$linkNum];
 }
Exemple #22
0
 /**
  * Connects to a database.
  * @return void
  * @throws DibiException
  */
 public function connect(array &$config)
 {
     if (isset($config['resource'])) {
         $this->connection = $config['resource'];
     } else {
         if (!isset($config['charset'])) {
             $config['charset'] = 'utf8';
         }
         if (isset($config['string'])) {
             $string = $config['string'];
         } else {
             $string = '';
             DibiConnection::alias($config, 'user', 'username');
             DibiConnection::alias($config, 'dbname', 'database');
             foreach (array('host', 'hostaddr', 'port', 'dbname', 'user', 'password', 'connect_timeout', 'options', 'sslmode', 'service') as $key) {
                 if (isset($config[$key])) {
                     $string .= $key . '=' . $config[$key] . ' ';
                 }
             }
         }
         DibiDriverException::tryError();
         if (empty($config['persistent'])) {
             $this->connection = pg_connect($string, PGSQL_CONNECT_FORCE_NEW);
         } else {
             $this->connection = pg_pconnect($string, PGSQL_CONNECT_FORCE_NEW);
         }
         if (DibiDriverException::catchError($msg)) {
             throw new DibiDriverException($msg, 0);
         }
     }
     if (!is_resource($this->connection)) {
         throw new DibiDriverException('Connecting error.');
     }
     if (isset($config['charset'])) {
         DibiDriverException::tryError();
         pg_set_client_encoding($this->connection, $config['charset']);
         if (DibiDriverException::catchError($msg)) {
             throw new DibiDriverException($msg, 0);
         }
     }
     if (isset($config['schema'])) {
         $this->query('SET search_path TO "' . $config['schema'] . '"');
     }
     $this->escMethod = version_compare(PHP_VERSION, '5.2.0', '>=');
 }
Exemple #23
0
 public function __construct($dsn)
 {
     $url_parts = parse_url($dsn);
     extract($url_parts, EXTR_SKIP);
     $name = substr($path, 1);
     $conn_str = "host={$host} port={$port} dbname={$name} user={$user} connect_timeout=8";
     if (isset($pass)) {
         $conn_str .= " password={$pass}";
     }
     $conn = pg_connect($conn_str);
     if ($conn === false) {
         throw new server_except("cannot connect to database: {$dsn}");
     }
     if (pg_set_client_encoding($conn, 'UTF8') !== 0) {
         throw new server_except('cannot set charset to utf8');
     }
     $this->conn = $conn;
 }
Exemple #24
0
 /**
  * コンストラクタ
  */
 public function __construct()
 {
     static $set_to_utf8 = false;
     // 設定の読み込み
     $ini = ic2_loadconfig();
     $this->_ini = $ini;
     if (!$ini['General']['dsn']) {
         p2die('DSNが設定されていません。');
     }
     // データベースへ接続
     $this->_database_dsn = $ini['General']['dsn'];
     $this->_db = $this->getDatabaseConnection();
     if (DB::isError($this->_db)) {
         p2die($this->_db->getMessage());
     }
     // クライアントの文字セットに UTF-8 を指定
     if (!$set_to_utf8) {
         if (preg_match('/^(\\w+)(?:\\((\\w+)\\))?:/', $this->_database_dsn, $m)) {
             $driver = strtolower($m[1]);
         } else {
             $driver = 'unknown';
         }
         switch ($driver) {
             case 'mysql':
             case 'mysqli':
                 if ($driver == 'mysql' && function_exists('mysql_set_charset')) {
                     mysql_set_charset('utf8', $this->_db->connection);
                 } elseif ($driver == 'mysqli' && function_exists('mysqli_set_charset')) {
                     mysqli_set_charset($this->_db->connection, 'utf8');
                 } else {
                     $this->_db->query("SET NAMES utf8");
                 }
                 break;
             case 'pgsql':
                 if (function_exists('pg_set_client_encoding')) {
                     pg_set_client_encoding($this->_db->connection, 'UNICODE');
                 } else {
                     $this->_db->query("SET CLIENT_ENCODING TO 'UNICODE'");
                 }
                 break;
         }
         $set_to_utf8 = true;
     }
 }
 protected function real_connect()
 {
     $hostname = $this->settings['hostname'];
     $username = $this->settings['username'];
     $password = $this->settings['password'];
     $database = $this->settings['database'];
     $encoding = $this->settings['encoding'];
     $connection_string = sprintf('host=%s dbname=%s user=%s password=%s', addslashes($hostname), addslashes($database), addslashes($username), addslashes($password));
     if ($this->settings['persistent']) {
         $this->connection_handle = pg_pconnect($connection_string, PGSQL_CONNECT_FORCE_NEW);
     } else {
         $this->connection_handle = pg_connect($connection_string, PGSQL_CONNECT_FORCE_NEW);
     }
     if (!$this->connection_handle) {
         throw new AnewtDatabaseConnectionException('Could not connect to PostgreSQL database');
     }
     if ($encoding) {
         pg_set_client_encoding($this->connection_handle, $encoding);
     }
 }
Exemple #26
0
 function connect()
 {
     if (!$this->Connected) {
         $this->Query_ID = 0;
         $cstr = "dbname='" . str_replace(array("\\", "'"), array("\\\\", "\\'"), $this->DBDatabase) . "'" . $this->ifadd($this->DBHost, "host=") . $this->ifadd($this->DBPort, "port=") . $this->ifadd($this->DBUser, "user="******"password="******"Cannot connect to database: " . pg_errormessage());
             return false;
         }
         if ($this->Encoding) {
             @pg_set_client_encoding($this->Link_ID, $this->Encoding);
         }
         $this->Connected = true;
     }
 }
Exemple #27
0
 /**
  * Db_Pgsql constructor.
  *
  * @param  array $args
  * @throws \Exception
  */
 public function __construct(array $args)
 {
     $this->args = $args;
     if (!is_callable('pgsql_connect')) {
         throw new \Exception(__METHOD__ . ': pgsql_connect is not supported.');
     }
     $this->conn = pg_connect(sprintf('host=%s user=%s password=%s dbname=%s', $args['host'], $args['user'], $args['pass'], $args['name']));
     if ($this->conn === false) {
         throw new \Exception(__METHOD__ . ': failed to connect to PostgreSQL server.');
     }
     $version = pg_version($this->conn);
     if (is_array($version) && isset($version['server'])) {
         $this->serverVersion = $this->getIntVersion($version['server']);
     } else {
         $this->serverVersion = 0;
     }
     if (!empty($args['charset'])) {
         pg_set_client_encoding($this->conn, $args['charset']);
     }
 }
 function connect($pconnect = false, $force_new = false)
 {
     if (is_resource($this->_conn)) {
         return;
     }
     $this->_last_err = null;
     $this->_last_err_code = null;
     $dsnstring = '';
     if (isset($this->_dsn['host'])) {
         $dsnstring = 'host=' . $this->_addslashes($this->_dsn['host']);
     }
     if (isset($this->_dsn['port'])) {
         $dsnstring .= ' port=' . $this->_addslashes($this->_dsn['port']);
     }
     if (isset($this->_dsn['login'])) {
         $dsnstring .= ' user='******'login']);
     }
     if (isset($this->_dsn['password'])) {
         $dsnstring .= ' password='******'password']);
     }
     if (isset($this->_dsn['database'])) {
         $dsnstring .= ' dbname=' . $this->_addslashes($this->_dsn['database']);
     }
     //$dsnstring .= ' ';
     if ($pconnect) {
         $this->_conn = pg_pconnect($dsnstring);
     } else {
         $this->_conn = pg_connect($dsnstring);
     }
     if (!is_resource($this->_conn)) {
         throw new QDB_Exception('CONNECT DATABASE', pg_errormessage(), 0);
     }
     //if (!$this->execute("set datestyle='ISO'")) { return false; }
     $charset = $this->_dsn['charset'];
     if (strtoupper($charset) == 'GB2312') {
         $charset = 'GBK';
     }
     if ($charset != '') {
         pg_set_client_encoding($this->_conn, $charset);
     }
 }
Exemple #29
0
 /**
  * Connects to a database.
  * @return void
  * @throws Dibi\Exception
  */
 public function connect(array &$config)
 {
     $error = NULL;
     if (isset($config['resource'])) {
         $this->connection = $config['resource'];
     } else {
         $config += ['charset' => 'utf8'];
         if (isset($config['string'])) {
             $string = $config['string'];
         } else {
             $string = '';
             Dibi\Helpers::alias($config, 'user', 'username');
             Dibi\Helpers::alias($config, 'dbname', 'database');
             foreach (['host', 'hostaddr', 'port', 'dbname', 'user', 'password', 'connect_timeout', 'options', 'sslmode', 'service'] as $key) {
                 if (isset($config[$key])) {
                     $string .= $key . '=' . $config[$key] . ' ';
                 }
             }
         }
         set_error_handler(function ($severity, $message) use(&$error) {
             $error = $message;
         });
         if (empty($config['persistent'])) {
             $this->connection = pg_connect($string, PGSQL_CONNECT_FORCE_NEW);
         } else {
             $this->connection = pg_pconnect($string, PGSQL_CONNECT_FORCE_NEW);
         }
         restore_error_handler();
     }
     if (!is_resource($this->connection)) {
         throw new Dibi\DriverException($error ?: 'Connecting error.');
     }
     pg_set_error_verbosity($this->connection, PGSQL_ERRORS_VERBOSE);
     if (isset($config['charset']) && pg_set_client_encoding($this->connection, $config['charset'])) {
         throw self::createException(pg_last_error($this->connection));
     }
     if (isset($config['schema'])) {
         $this->query('SET search_path TO "' . $config['schema'] . '"');
     }
 }
 function connect($db)
 {
     $connection_string = array();
     if ($db['server']) {
         if ($db['port']) {
             $connection_string[] = 'port=' . $db['port'];
         }
         $connection_string[] = 'host=' . $db['server'];
     }
     if ($db['username']) {
         $connection_string[] = 'user='******'username'];
     }
     if ($db['password']) {
         $connection_string[] = 'password='******'password'];
     }
     if ($db['database']) {
         $connection_string[] = 'dbname=' . $db['database'];
     }
     if ($this->link_identifier) {
         $this->disconnect();
     }
     $connection_string = implode(' ', $connection_string);
     $this->link_identifier = $db['persistent'] ? @pg_pconnect($connection_string) : @pg_connect($connection_string);
     if ($this->link_identifier) {
         if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
             pg_set_client_encoding($this->link_identifier, 'UNICODE');
             //pg_set_client_encoding($this->link_identifier, 'UTF8');  pg8.1 unicode still works tho
             //pg_query($this->link_identifier, "SET CLIENT_ENCODING TO 'UNICODE'"); SET NAMES 'UNICODE'
         }
         return $this->link_identifier;
     }
     if (!$this->report_error) {
         return false;
     }
     $error = '<center>There is currently a problem with the site<br/>Please try again later<br /><br />Error Code: DB1</center>';
     $this->disconnect();
     trigger_error($error, E_USER_ERROR);
 }