public function __construct($config) { include_once "core/dbsimple/Generic.php"; $this->rDB = DbSimple_Generic::connect($config['rdb']); $this->rDB->setErrorHandler("databaseErrorHandler"); $this->rDB->query("SET NAMES ? ", $config['db_encoding']); }
public function __construct() { global $g_config; // Подключаем модули для работы с DbSimple (не по подгрузится автолоудером) $path = dirname(__FILE__) . '/DbSimple/'; require_once $path . 'Generic.php'; require_once $path . 'Mysql.php'; require_once $path . 'Postgresql.php'; require_once $path . 'my/MyDataBaseLog.php'; $dbs = $g_config['dbSimple']['databases']; // Собираем все объекты в $o $o = new stdClass(); foreach ($dbs as $db => $conn) { $dsn = $conn['dsn']; $cacheFunc = isset($conn['pCacheFunc']) ? $conn['pCacheFunc'] : NULL; $o->{$db} = DbSimple_Generic::connect($dsn); if ($g_config['dbSimple']['logDbError']) { MyDataBaseLog::SetFuncOnError(array(__CLASS__, 'DbSimpleError')); $o->{$db}->setLogger(array('MyDataBaseLog', 'Log')); $o->{$db}->setErrorHandler(array('MyDataBaseLog', 'Error')); } if ($cacheFunc) { $o->{$db}->setCacher($cacheFunc); } } // Регистрируем все базы данных как объект $g_databases $GLOBALS['g_databases'] = $o; }
/** * constructor(string $dsn) * Connect to MySQL. */ function DbSimple_Mysql($dsn) { $this->dsn = DbSimple_Generic::parseDSN($dsn); if (!is_callable('mysql_connect')) { return $this->_setLastError("-1", "MySQL extension is not loaded", "mysql_connect"); } }
function db_connect($hostName, $userName, $dbPassword, $dbName) { // Подключаемся к БД. $dbc = DbSimple_Generic::connect('mysqli://' . $userName . ':' . $dbPassword . '@' . $hostName . '/' . $dbName); $dbc->query('set names ?', 'utf8'); return $dbc; }
/** * DbSimple_Generic connect(mixed $dsn) * * Universal static function to connect ANY database using DSN syntax. * Choose database driver according to DSN. Return new instance * of this driver. */ function &connect($dsn) { // Load database driver and create its instance. $parsed = DbSimple_Generic::parseDSN($dsn); if (!$parsed) { $dummy = null; return $dummy; } $class = 'DbSimple_' . ucfirst($parsed['scheme']); if (!class_exists($class)) { $file = str_replace('_', '/', $class) . ".php"; // Try to load library file from standard include_path. if ($f = @fopen($file, "r", true)) { fclose($f); require_once $file; } else { // Wrong include_path; try to load from current directory. $base = basename($file); $dir = dirname(__FILE__); if (@is_file($path = "{$dir}/{$base}")) { require_once $path; } else { trigger_error("Error loading database driver: no file {$file} in include_path; no file {$base} in {$dir}", E_USER_ERROR); return null; } } } $object =& new $class($parsed); if (isset($parsed['ident_prefix'])) { $object->setIdentPrefix($parsed['ident_prefix']); } return $object; }
function __construct() { require_once "dbsimple/config.php"; require_once "dbsimple/DbSimple/Generic.php"; require_once "data_connection.php"; $this->db = @DbSimple_Generic::connect('mysqli://' . $UserName . ':' . $Password . '@' . $ServerName . '/' . $Database); }
function __construct($file = null) { global $db_config; include_once 'dbsimple/Generic.php'; // including simple conecting for DB $this->DB = DbSimple_Generic::connect($db_config['dbc_dns']); $this->DB->setErrorHandler("databaseErrorHandler"); // $this->DB->setLogger("databaseLogHandler"); // $this->DB->setIdentPrefix($db_config['db_prefix']); $this->initDB(); if ($file == null) { return; } if ($this->file = fopen(self::$_dir . $file, "rb")) { $ex = explode('.', $file); $this->name = $ex[0]; $this->dom = new DOMDocument(); $this->dom->preserveWhiteSpace = false; $this->dom->substituteEntities = true; $xmlfile = 'xml/' . $this->name . '.xml'; if (file_exists($xmlfile)) { $this->dom->Load($xmlfile); $this->XML = $this->dom->getElementsByTagName('file')->item(0); $this->format = $this->XML->getAttribute('format'); return; } } else { $this->error = sprintf($this->_STR['FILE_NOT_EXISTS'], $file); } }
/** * Constructor */ private function __construct() { $connection = DbSimple_Generic::connect('mysqli://' . DB_USER . ':' . DB_PASS . '@' . DB_SERVER . '/' . DB_NAME); $connection->query("SET names utf8"); $connection->setErrorHandler('dbErrorHandler'); $connection->setLogger('dbLogger'); }
/** * Initialize database & template handlers, sets up sql/site configs * @category Main system functions * @example Connector::__construct() * @return bool **/ public function __construct() { include 'configuration.php'; require_once 'libs/DbSimple/Generic.php'; require_once 'libs/Smarty-2.6.26/Smarty.class.php'; $this->mysqlconfig = $ArmoryConfig['mysql']; $this->armoryconfig = $ArmoryConfig['settings']; $this->aDB = DbSimple_Generic::connect('mysql://' . $this->mysqlconfig['user_armory'] . ':' . $this->mysqlconfig['pass_armory'] . '@' . $this->mysqlconfig['host_armory'] . '/' . $this->mysqlconfig['name_armory']); $this->cDB = DbSimple_Generic::connect('mysql://' . $this->mysqlconfig['user_characters'] . ':' . $this->mysqlconfig['pass_characters'] . '@' . $this->mysqlconfig['host_characters'] . '/' . $this->mysqlconfig['name_characters']); $this->rDB = DbSimple_Generic::connect('mysql://' . $this->mysqlconfig['user_realmd'] . ':' . $this->mysqlconfig['pass_realmd'] . '@' . $this->mysqlconfig['host_realmd'] . '/' . $this->mysqlconfig['name_realmd']); $this->wDB = DbSimple_Generic::connect('mysql://' . $this->mysqlconfig['user_mangos'] . ':' . $this->mysqlconfig['pass_mangos'] . '@' . $this->mysqlconfig['host_mangos'] . '/' . $this->mysqlconfig['name_mangos']); /* temporary disabled // Test connection if(!$this->aDB->selectCell("SELECT `id` FROM `classes` LIMIT 1")) { $this->databaseError('Can not execute query to armory database ("<i>%s</i>")!<br />Check you configuration.php for correct values.', $this->mysqlconfig['name_armory']); } if(!$this->cDB->selectCell("SELECT `guid` FROM `characters` LIMIT 1")) { $this->databaseError('Can not execute query to characters database ("<i>%s</i>")!<br />Check you configuration.php for correct values.', $this->mysqlconfig['name_characters']); } if(!$this->rDB->selectCell("SELECT `name` FROM `realmlist` LIMIT 1")) { $this->databaseError('Can not execute query to realmd database ("<i>%s</i>")!<br />Check you configuration.php for correct values.', $this->mysqlconfig['name_realmd']); } if(!$this->wDB->selectCell("SELECT `entry` FROM `item_template` LIMIT 1")) { $this->databaseError('Can not execute query to mangos database ("<i>%s</i>")!<br />Check you configuration.php for correct values.', $this->mysqlconfig['name_mangos']); } */ $this->aDB->query("SET NAMES ?", $this->mysqlconfig['charset_armory']); $this->cDB->query("SET NAMES ?", $this->mysqlconfig['charset_characters']); $this->rDB->query("SET NAMES ?", $this->mysqlconfig['charset_realmd']); $this->wDB->query("SET NAMES ?", $this->mysqlconfig['charset_mangos']); $this->tpl = new Smarty(); return true; }
function BDConnect() { $db = DbSimple_Generic::connect("mysqli://{$this->user}:{$this->pass}@{$this->host}/{$this->bd_name}"); $db->query("SET NAMES utf8"); $db->setErrorHandler('databaseErrorHandler'); $db->setLogger('myLogger'); return $db; }
/** * constructor(string $dsn) * Connect to MySQL. */ function DbSimple_Mysql($dsn) { $DbSimple_Generic = new DbSimple_Generic(); // $p = DbSimple_Generic::parseDSN($dsn); $p = $DbSimple_Generic->parseDSN($dsn); if (!is_callable('mysql_connect')) { return $this->_setLastError("-1", "MySQL extension is not loaded", "mysql_connect"); } $ok = $this->link = @mysql_connect($p['host'] . (empty($p['port']) ? "" : ":" . $p['port']), $p['user'], $p['pass'], true); $this->_resetLastError(); if (!$ok) { return $this->_setDbError('mysql_connect()'); } $ok = @mysql_select_db(preg_replace('{^/}s', '', $p['path']), $this->link); if (!$ok) { return $this->_setDbError('mysql_select_db()'); } }
public function __construct($ini_file_name) { if (!($ini_array = $this->get_params_from_ini_file($ini_file_name))) { echo 'Отсутствует ' . $this->ini_file_name . ' файл. Перейдите к <a href="install.php">установке</a>'; exit; } $this->db = DbSimple_Generic::connect('mysqli://' . $ini_array['UserName'] . ':' . $ini_array['Password'] . '@' . $ini_array['ServerName'] . '/' . $ini_array['Database']); $this->db->setErrorHandler('databaseErrorHandler'); $this->db->setLogger('myLogger'); }
public function connectDB() { // Подключаемся к БД. $db = DbSimple_Generic::connect("mysqli://{$this->db_user}:{$this->db_password}@{$this->db_host}/{$this->db_name}"); $db->query("SET NAMES utf8"); // Устанавливаем обработчик ошибок. $db->setErrorHandler('installErrorHandler'); $db->setLogger('myLogger'); return $db; }
/** * constructor(string $dsn) * Connect to MySQL. */ function DbSimple_Mysql($dsn) { $DbSimple = new DbSimple_Generic(); $p = $DbSimple->parseDSN($dsn); if (!is_callable('mysql_connect')) { return $this->_setLastError("-1", "MySQL extension is not loaded", "mysql_connect"); } $ok = $this->link = @mysql_connect($str = $p['host'] . (empty($p['port']) ? "" : ":" . $p['port']), $p['user'], $p['pass'], true); $this->_resetLastError(); if (!$ok) { return $this->_setDbError('mysql_connect("' . $str . '", "' . $p['user'] . '")'); } $ok = @mysql_select_db(preg_replace('{^/}s', '', $p['path']), $this->link); if (!$ok) { return $this->_setDbError('mysql_select_db()'); } if (isset($p["charset"])) { $this->query('SET NAMES ?', $p["charset"]); } }
function &connectMysql($conf) { global $config; require_once $config['root_dir'] . '/includes/dbsimple/Generic.php'; require_once $config['root_dir'] . '/includes/dbsimple/Mysql.php'; extract($conf); $database =& DbSimple_Generic::connect(array('scheme' => 'mysql', 'user' => $user, 'pass' => $pass, 'host' => $host, 'path' => $db)); $database->setErrorHandler('defaultDatabaseErrorHandler'); $database->setIdentPrefix($prefix); return $database; }
/** * constructor(string $dsn) * Connect to Interbase/Firebird. */ function DbSimple_Ibase($dsn) { $p = DbSimple_Generic::parseDSN($dsn); if (!is_callable('ibase_connect')) { return $this->_setLastError("-1", "Interbase/Firebird extension is not loaded", "ibase_connect"); } $ok = $this->link = ibase_connect($p['host'] . (empty($p['port']) ? "" : ":" . $p['port']) . ':' . preg_replace('{^/}s', '', $p['path']), $p['user'], $p['pass'], isset($p['CHARSET']) ? $p['CHARSET'] : 'win1251', isset($p['BUFFERS']) ? $p['BUFFERS'] : 0, isset($p['DIALECT']) ? $p['DIALECT'] : 3, isset($p['ROLE']) ? $p['ROLE'] : ''); $this->_resetLastError(); if (!$ok) { return $this->_setDbError('ibase_connect()'); } }
/** * constructor(string $dsn) * Connect to PostgresSQL. */ function DbSimple_Postgresql($dsn) { $p = DbSimple_Generic::parseDSN($dsn); if (!is_callable('pg_connect')) { return $this->_setLastError("-1", "PostgreSQL extension is not loaded", "pg_connect"); } $ok = $this->link = @pg_connect($t = (!empty($p['host']) ? 'host=' . $p['host'] . ' ' : '') . (!empty($p['port']) ? 'port=' . $p['port'] . ' ' : '') . 'dbname=' . preg_replace('{^/}s', '', $p['path']) . ' ' . (!empty($p['user']) ? 'user='******'user'] . ' ' : '') . (!empty($p['pass']) ? 'password='******'pass'] . ' ' : '')); $this->_resetLastError(); if (!$ok) { return $this->_setDbError('pg_connect()'); } }
/** * Получает объект БД * * @param array $aConfig - конфиг подключения к БД(хост, логин, пароль, тип бд, имя бд) * @return DbSimple */ public function GetConnect($aConfig = null) { /** * Если конфиг не передан то используем главный конфиг БД из config.php */ if (is_null($aConfig)) { $aConfig = Config::Get('db.params'); } $sDSN = $aConfig['type'] . 'wrapper://' . $aConfig['user'] . ':' . $aConfig['pass'] . '@' . $aConfig['host'] . ':' . $aConfig['port'] . '/' . $aConfig['dbname']; /** * Создаём хеш подключения, уникальный для каждого конфига */ $sDSNKey = md5($sDSN); /** * Проверяем создавали ли уже коннект с такими параметрами подключения(DSN) */ if (isset($this->aInstance[$sDSNKey])) { return $this->aInstance[$sDSNKey]; } else { /** * Если такого коннекта еще не было то создаём его */ $oDbSimple = DbSimple_Generic::connect($sDSN); /** * Устанавливаем хук на перехват ошибок при работе с БД */ $oDbSimple->setErrorHandler('databaseErrorHandler'); /** * Если нужно логировать все SQL запросы то подключаем логгер */ if (Config::Get('sys.logs.sql_query')) { $oDbSimple->setLogger('databaseLogger'); } /** * Устанавливаем настройки соединения, по хорошему этого здесь не должно быть :) * считайте это костылём */ $oDbSimple->query("set character_set_client='utf8'"); $oDbSimple->query("set character_set_results='utf8'"); $oDbSimple->query("set collation_connection='utf8_bin'"); /** * Сохраняем коннект */ $this->aInstance[$sDSNKey] = $oDbSimple; /** * Возвращаем коннект */ return $oDbSimple; } }
/** * constructor(string $dsn) * Connect to PostgresSQL. */ function DbSimple_Postgresql($dsn) { $p = DbSimple_Generic::parseDSN($dsn); if (!is_callable('pg_connect')) { return $this->_setLastError("-1", "PostgreSQL extension is not loaded", "pg_connect"); } // Prepare+execute works only in PHP 5.1+. $this->DbSimple_Postgresql_USE_NATIVE_PHOLDERS = function_exists('pg_prepare'); $ok = $this->link = @pg_connect($t = (!empty($p['host']) ? 'host=' . $p['host'] . ' ' : '') . (!empty($p['port']) ? 'port=' . $p['port'] . ' ' : '') . 'dbname=' . preg_replace('{^/}s', '', $p['path']) . ' ' . (!empty($p['user']) ? 'user='******'user'] . ' ' : '') . (!empty($p['pass']) ? 'password='******'pass'] . ' ' : '')); $this->_resetLastError(); if (!$ok) { return $this->_setDbError('pg_connect()'); } }
function &connect($dsn) { $parsed = DbSimple_Generic::parseDSN($dsn); if (!$parsed) { $dummy = null; return $dummy; } $class = 'DbSimple_' . ucfirst($parsed['scheme']); if (!class_exists($class)) { $file = str_replace('_', '/', $class) . ".php"; if ($f = @fopen($file, "r", true)) { fclose($f); require_once $file; } else { $base = basename($file); $dir = dirname(__FILE__); if (@is_file($path = "{$dir}/{$base}")) { require_once $path; } else { trigger_error("Error loading database driver: no file {$file} in include_path; no file {$base} in {$dir}", E_USER_ERROR); return null; } } } $object =& new $class($parsed); if (isset($parsed['ident_prefix'])) { $object->setIdentPrefix($parsed['ident_prefix']); } $object->setCachePrefix(md5(serialize($parsed['dsn']))); if (@fopen('Cache/Lite.php', 'r', true)) { $tmp_dirs = array(ini_get('session.save_path'), getenv("TEMP"), getenv("TMP"), getenv("TMPDIR"), '/tmp'); foreach ($tmp_dirs as $dir) { if (!$dir) { continue; } $fp = @fopen($testFile = $dir . '/DbSimple_' . md5(getmypid() . microtime()), 'w'); if ($fp) { fclose($fp); unlink($testFile); require_once 'Cache' . '/Lite.php'; // "." -> no phpEclipse notice $t =& new Cache_Lite(array('cacheDir' => $dir . '/', 'lifeTime' => null, 'automaticSerialization' => true)); $object->_cacher =& $t; break; } } } return $object; }
private function _boot() { session_start(); ob_start(); $this->_oConfig = new Config($this->_sConfigFile); setlocale(LC_ALL, $this->config->project->locale); require_once $_SERVER['DOCUMENT_ROOT'] . $this->config->db->lib_path . '/Generic.php'; require_once $_SERVER['DOCUMENT_ROOT'] . $this->config->db->lib_path . '/Mysql.php'; $this->_oDb = \DbSimple_Generic::connect("mysql://" . $this->config->db->user . ($this->config->db->password ? ":" . $this->config->db->password : '') . "@" . $this->config->db->host . "/" . $this->config->db->database); $this->db->setIdentPrefix($this->config->db->table_prefix); $this->db->query("SET NAMES utf8"); $oRoutesConfig = new Config($_SERVER['DOCUMENT_ROOT'] . $this->config->router->path); $this->_oRequest = new Request($oRoutesConfig->routes); $this->_oView = new View($this->config->templates->path, $this->_oRequest->lang); $this->_oDirector = new Director($this->options); }
/** * Возвращает экземпляр класса для подключения к бд * * @param string $dbAlias * @return DbSimple_Generic */ public static function get($dbAlias) { if (!isset(self::$_instances[$dbAlias])) { $db = DbSimple_Generic::connect(self::$_configs[$dbAlias]['connectUri']); if (self::$_configs[$dbAlias]['initSQL']) { $db->query(self::$_configs[$dbAlias]['initSQL']); } $db->setErrorHandler(array(__CLASS__, 'databaseErrorHandler')); $db->addIgnoreInTrace(__CLASS__ . '::databaseErrorHandler'); if (self::$_configs[$dbAlias]['debug']) { $db->setLogger(array(__CLASS__, 'databaseLogger')); $db->addIgnoreInTrace(__CLASS__ . '::databaseLogger'); } self::$_instances[$dbAlias] = $db; } return self::$_instances[$dbAlias]; }
function __construct() { global $config; include_once dirname(__FILE__) . '/dbsimple/Generic.php'; $this->cDB = DbSimple_Generic::connect($config['cdb']); $this->cDB->setErrorHandler("databaseErrorHandler"); $this->cDB->query("SET NAMES ? ", $config['db_encoding']); $this->rDB = DbSimple_Generic::connect($config['rdb']); $this->rDB->setErrorHandler("databaseErrorHandler"); $this->rDB->query("SET NAMES ? ", $config['db_encoding']); $this->wDB = DbSimple_Generic::connect($config['wdb']); $this->wDB->setErrorHandler("databaseErrorHandler"); $this->wDB->query("SET NAMES ? ", $config['db_encoding']); if ($config['buildClient'] < 11723) { print "Некорректно настроен конфиг. Неизвесная сборка клиента (" . $config['buildClient'] . ")"; } }
/** * Получает объект БД * * @param array|null $aConfig - конфиг подключения к БД(хост, логин, пароль, тип бд, имя бд), если null, то используются параметры из конфига Config::Get('db.params') * @param bool $bForce Создавать принудительно новый коннект, даже если он уже существует * @return DbSimple_Generic_Database DbSimple */ public function GetConnect($aConfig = null, $bForce = false) { /** * Получаем DSN */ $sDSN = $this->GetDSNByConfig($aConfig); /** * Создаём хеш подключения, уникальный для каждого конфига */ $sDSNKey = md5($sDSN); /** * Проверяем создавали ли уже коннект с такими параметрами подключения(DSN) */ if (isset($this->aInstance[$sDSNKey]) and !$bForce) { return $this->aInstance[$sDSNKey]; } else { /** * Если такого коннекта еще не было то создаём его */ $oDbSimple = DbSimple_Generic::connect($sDSN); /** * Устанавливаем хук на перехват ошибок при работе с БД */ $oDbSimple->setErrorHandler(array($this, 'CallbackError')); /** * Если нужно логировать все SQL запросы то подключаем логгер */ if (Config::Get('sys.logs.sql_query')) { $oDbSimple->setLogger(array($this, 'CallbackQuery')); } /** * Устанавливаем настройки соединения, по хорошему этого здесь не должно быть :) * считайте это костылём */ $oDbSimple->query("set character_set_client='utf8', character_set_results='utf8', collation_connection='utf8_bin' "); /** * Сохраняем коннект */ $this->aInstance[$sDSNKey] = $oDbSimple; /** * Возвращаем коннект */ return $oDbSimple; } }
public static function connect($idx) { if (self::isConnected($idx)) { return; } $options =& self::$optionsCache[$idx]; $interface = DbSimple_Generic::connect(self::createConnectSyntax($options)); if (!$interface || $interface->error) { die('Failed to connect to database.'); } $interface->setErrorHandler(['DB', 'errorHandler']); $interface->query('SET NAMES ?', 'utf8'); if ($options['prefix']) { $interface->setIdentPrefix($options['prefix']); } self::$interfaceCache[$idx] =& $interface; self::$connectionCache[$idx] = true; }
private function __construct() { require_once "./lib/dbsimple/config.php"; require_once "./lib/dbsimple/DbSimple/Generic.php"; //проверим заполнен ли конфигурационный файл с подключением к БД в случае ошибки перенаправим на установку if (!file_get_contents('base.conf')) { header('Location: http://' . $_SERVER['HTTP_HOST'] . '/install'); exit; } $this->getConfig(); //получаем конфиг к подключению к базе данных $this->db = DbSimple_Generic::connect("mysql://{$this->_conf['user_name']}:{$this->_conf['password']}@{$this->_conf['server_name']}/{$this->_conf['database']}"); //в случае возникновения ошибки if (!empty($this->db->error)) { $this->db = $this->databaseError($this->db->error['code'], $this->db->error['message']); return $this->db; } $this->db->query("SET NAMES UTF8"); }
protected function _getDbConnect($sDsn) { if (Config::Get('db.params.lazy')) { // lazy connection //F::IncludeLib('DbSimple3/lib/DbSimple/Connect.php'); $oDbSimple = new DbSimple_Connect($sDsn); foreach ($this->aInitSql as $sSql) { $oDbSimple->addInit($sSql); } } else { // immediate connection //F::IncludeLib('DbSimple3/lib/DbSimple/Generic.php'); $oDbSimple = DbSimple_Generic::connect($sDsn); foreach ($this->aInitSql as $sSql) { $oDbSimple->query($sSql); } } return $oDbSimple; }
function initialize(IConfigParameter $configuration) { $dsn = $configuration->get('DSN'); if (!$dsn) { $connection_file = $configuration->get('connection_file'); if (!$connection_file) { throw new DbException("Connection file not defined"); } $p = pathinfo($connection_file); $dir = Project::NS()->path($p['dirname']); $f = $dir . $p['basename']; if (!file_exists($f) || !is_file($f)) { throw new DbException("Connection file not exists"); } $config = new ConfigParameter(file_get_contents($f)); $dsn = $config->get('DSN'); if (!$dsn) { throw new DbException("DSN not exitsts at connection file"); } } $this->_caching = $configuration->get('caching'); if ($configuration->get('cache_prefix')) { $this->_cache_prefix = $configuration->get('cache_prefix'); } if ($configuration->get('cache_module_id')) { $this->_cache_module_id = $configuration->get('cache_module_id'); } else { // No cache module defined // TODO:: write NOTICE to log $this->_caching = false; } $this->_DSN = $dsn; $this->_common_config($configuration); $this->_driver = DbSimple_Generic::connect($this->_DSN); if (!is_object($this->_driver)) { throw new DbException("No connection to database"); } $this->_driver->query("SET NAMES utf8"); $this->_driver->setLogger($configuration->get('native_logger')); //$this -> _driver -> setLogger('myLogger'); Project::setDatabase($this); }
/** * constructor(string $dsn) * Connect to MySQL. */ function DbSimple_Mysql($dsn) { $p = DbSimple_Generic::parseDSN($dsn); if (!is_callable('mysql_connect')) { return $this->_setLastError("-1", "MySQL extension is not loaded", "mysql_connect"); } $ok = $this->link = @mysql_connect($p['host'] . (empty($p['port']) ? "" : ":" . $p['port']), $p['user'], $p['pass'], true); $this->_resetLastError(); if (!$ok) { return $this->_setDbError('mysql_connect()'); } // aMember custom code if ($charset = $GLOBALS['config']['db']['mysql']['charset']) { mysql_set_charset($charset, $this->link); } $ok = @mysql_select_db(preg_replace('{^/}s', '', $p['path']), $this->link); if (!$ok) { return $this->_setDbError('mysql_select_db()'); } }
/** * constructor(string $dsn) * Connect to PostgresSQL. */ function DbSimple_Postgresql($dsn) { $p = DbSimple_Generic::parseDSN($dsn); if (!is_callable('pg_connect')) { return $this->_setLastError("-1", "PostgreSQL extension is not loaded", "pg_connect"); } // Prepare+execute works only in PHP 5.1+. $this->DbSimple_Postgresql_USE_NATIVE_PHOLDERS = function_exists('pg_prepare'); $dsnWithoutPass = (!empty($p['host']) ? 'host=' . $p['host'] . ' ' : '') . (!empty($p['port']) ? 'port=' . $p['port'] . ' ' : '') . 'dbname=' . preg_replace('{^/}s', '', $p['path']) . ' ' . (!empty($p['user']) ? 'user='******'user'] : ''); $ok = $this->link = @pg_connect($dsnWithoutPass . " " . (!empty($p['pass']) ? 'password='******'pass'] . ' ' : ''), PGSQL_CONNECT_FORCE_NEW); // We use PGSQL_CONNECT_FORCE_NEW, because in PHP 5.3 & PHPUnit // $this->prepareCache may be cleaned, but $this->link is still // not closed. So the next creation of DbSimple_Postgresql() // would use exactly the same connection as the previous, but with // empty $this->prepareCache, and it will generate "prepared statement // xxx already exists" error each time we execute the same statement // as in the previous calls. $this->_resetLastError(); if (!$ok) { return $this->_setDbError('pg_connect("' . $dsnWithoutPass . '") error'); } }