/** * Establishes a connection to the database. * Includes php_interface/after_connect_d7.php on success. * Throws exception on failure. * * @return void * @throws \Bitrix\Main\DB\ConnectionException */ protected function connectInternal() { if ($this->isConnected) { return; } $connectionInfo = array("UID" => $this->login, "PWD" => $this->password, "Database" => $this->database, "ReturnDatesAsStrings" => true); if (($this->options & self::PERSISTENT) != 0) { $connectionInfo["ConnectionPooling"] = true; } else { $connectionInfo["ConnectionPooling"] = false; } $connection = sqlsrv_connect($this->host, $connectionInfo); if (!$connection) { throw new ConnectionException('MS Sql connect error', $this->getErrorMessage()); } $this->resource = $connection; $this->isConnected = true; // hide cautions sqlsrv_configure("WarningsReturnAsErrors", 0); /** @noinspection PhpUnusedLocalVariableInspection */ global $DB, $USER, $APPLICATION; if ($fn = \Bitrix\Main\Loader::getPersonal("php_interface/after_connect_d7.php")) { include $fn; } }
/** * @param string $serverName * @param array $connectionOptions * * @throws \Doctrine\DBAL\Driver\SQLSrv\SQLSrvException */ public function __construct($serverName, $connectionOptions) { if (!sqlsrv_configure('WarningsReturnAsErrors', 0)) { throw SQLSrvException::fromSqlSrvErrors(); } $this->conn = sqlsrv_connect($serverName, $connectionOptions); if (!$this->conn) { throw SQLSrvException::fromSqlSrvErrors(); } $this->lastInsertId = new LastInsertId(); }
/** * Constructor. * * @param array $options List of options used to configure the connection * * @return void * * @since 11.1 */ protected function __construct($options) { // Get some basic values from the options. $options['host'] = isset($options['host']) ? $options['host'] : 'localhost'; $options['user'] = isset($options['user']) ? $options['user'] : ''; $options['password'] = isset($options['password']) ? $options['password'] : ''; $options['database'] = isset($options['database']) ? $options['database'] : ''; $options['select'] = isset($options['select']) ? (bool) $options['select'] : true; // Build the connection configuration array. $config = array('Database' => $options['database'], 'uid' => $options['user'], 'pwd' => $options['password'], 'CharacterSet' => 'UTF-8', 'ReturnDatesAsStrings' => true); // Make sure the SQLSRV extension for PHP is installed and enabled. if (!function_exists('sqlsrv_connect')) { // Legacy error handling switch based on the JError::$legacy switch. // @deprecated 11.3 if (JError::$legacy) { $this->errorNum = 1; $this->errorMsg = JText::_('JLIB_DATABASE_ERROR_ADAPTER_SQLSRV'); return; } else { throw new DatabaseException(JText::_('JLIB_DATABASE_ERROR_ADAPTER_SQLSRV')); } } // Attempt to connect to the server. if (!($this->connection = @sqlsrv_connect($options['host'], $config))) { // Legacy error handling switch based on the JError::$legacy switch. // @deprecated 11.3 if (JError::$legacy) { $this->errorNum = 2; $this->errorMsg = JText::_('JLIB_DATABASE_ERROR_CONNECT_SQLSRV'); return; } else { throw new DatabaseException(JText::_('JLIB_DATABASE_ERROR_CONNECT_SQLSRV')); } } // Make sure that DB warnings are not returned as errors. sqlsrv_configure('WarningsReturnAsErrors', 0); // Finalize initialisation parent::__construct($options); // If auto-select is enabled select the given database. if ($options['select'] && !empty($options['database'])) { $this->select($options['database']); } }
/** * Connect to the database. * * @throws <b>AgaviDatabaseException</b> If a connection could not be * created. * * @author David Zülke <*****@*****.**> * @since 1.0.4 */ protected function connect() { $serverName = $this->getParameter('server_name'); if ($serverName == null) { // missing required server_name parameter $error = 'Database configuration is missing "server_name" parameter'; throw new AgaviDatabaseException($error); } $settings = array(); if ($this->hasParameter('settings')) { foreach ((array) $this->getParameter('settings') as $key => $value) { if (!sqlsrv_configure($key, is_string($value) && strpos($value, 'SQLSRV_') === 0 && defined($value) ? constant($value) : (is_numeric($value) ? (int) $value : $value))) { throw new AgaviDatabaseException(sprintf('Unsupported key or value for setting "%s".', $key)); } } } $connectionInfo = $this->getParameter('connection_info'); foreach ($connectionInfo as $key => &$value) { $value = is_string($value) && strpos($value, 'SQLSRV_') === 0 && defined($value) ? constant($value) : (is_numeric($value) ? (int) $value : $value); } $this->connection = sqlsrv_connect($serverName, $connectionInfo); if (!$this->connection) { $this->connection = null; $errors = sqlsrv_errors(); foreach ($errors as &$error) { if (strtolower($this->getParameter('connection_info[CharacterSet]')) != 'utf-8' || version_compare(phpversion('sqlsrv'), '2', 'lt')) { // even when UTF-8 is specified as the encoding for the connection, error messages will be returned in the local codepage in ext/sqlsrv 1.x // (not just for connection failures, but also for failed queries etc) // also, we need to convert the encoding for newer versions as well if the encoding on the connection was not UTF-8 $error['message'] = utf8_encode($error['message']); } $error = sprintf('SQLSTATE %s (code %d): %s', $error['SQLSTATE'], $error['code'], $error['message']); } throw new AgaviDatabaseException(sprintf("%s\n\n%s", sprintf('Could not open database connection "%s".', $this->getName()), implode("\n", $errors))); } foreach ((array) $this->getParameter('init_queries') as $query) { sqlsrv_query($this->connection, $query); } }
/** * Connect to db * Must be called before most other methods. (you can call methods that return connection configuration parameters) * @param string $dbhost The database host. * @param string $dbuser The database username. * @param string $dbpass The database username's password. * @param string $dbname The name of the database being connected to. * @param mixed $prefix string|bool The moodle db table name's prefix. false is used for external databases where prefix not used * @param array $dboptions driver specific options * @return bool true * @throws dml_connection_exception if error */ public function connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions = null) { if ($prefix == '' and !$this->external) { // Enforce prefixes for everybody but mysql. throw new dml_exception('prefixcannotbeempty', $this->get_dbfamily()); } $driverstatus = $this->driver_installed(); if ($driverstatus !== true) { throw new dml_exception('dbdriverproblem', $driverstatus); } /* * Log all Errors. */ sqlsrv_configure("WarningsReturnAsErrors", FALSE); sqlsrv_configure("LogSubsystems", SQLSRV_LOG_SYSTEM_OFF); sqlsrv_configure("LogSeverity", SQLSRV_LOG_SEVERITY_ERROR); $this->store_settings($dbhost, $dbuser, $dbpass, $dbname, $prefix, $dboptions); $this->sqlsrv = sqlsrv_connect($this->dbhost, array('UID' => $this->dbuser, 'PWD' => $this->dbpass, 'Database' => $this->dbname, 'CharacterSet' => 'UTF-8', 'MultipleActiveResultSets' => true, 'ConnectionPooling' => !empty($this->dboptions['dbpersist']), 'ReturnDatesAsStrings' => true)); if ($this->sqlsrv === false) { $this->sqlsrv = null; $dberr = $this->get_last_error(); throw new dml_connection_exception($dberr); } // Allow quoted identifiers $sql = "SET QUOTED_IDENTIFIER ON"; $this->query_start($sql, null, SQL_QUERY_AUX); $result = sqlsrv_query($this->sqlsrv, $sql); $this->query_end($result); $this->free_result($result); // Force ANSI nulls so the NULL check was done by IS NULL and NOT IS NULL // instead of equal(=) and distinct(<>) symbols $sql = "SET ANSI_NULLS ON"; $this->query_start($sql, null, SQL_QUERY_AUX); $result = sqlsrv_query($this->sqlsrv, $sql); $this->query_end($result); $this->free_result($result); // Force ANSI warnings so arithmetic/string overflows will be // returning error instead of transparently truncating data $sql = "SET ANSI_WARNINGS ON"; $this->query_start($sql, null, SQL_QUERY_AUX); $result = sqlsrv_query($this->sqlsrv, $sql); $this->query_end($result); // Concatenating null with anything MUST return NULL $sql = "SET CONCAT_NULL_YIELDS_NULL ON"; $this->query_start($sql, null, SQL_QUERY_AUX); $result = sqlsrv_query($this->sqlsrv, $sql); $this->query_end($result); $this->free_result($result); // Set transactions isolation level to READ_COMMITTED // prevents dirty reads when using transactions + // is the default isolation level of sqlsrv $sql = "SET TRANSACTION ISOLATION LEVEL READ COMMITTED"; $this->query_start($sql, NULL, SQL_QUERY_AUX); $result = sqlsrv_query($this->sqlsrv, $sql); $this->query_end($result); $this->free_result($result); // Connection established and configured, going to instantiate the temptables controller $this->temptables = new sqlsrv_native_moodle_temptables($this); return true; }
public function open() { if (is_resource($this->connection)) { return; } $config = $this->connectionConfig; // Make sure the SQLSRV extension for PHP is installed and enabled. if (!function_exists('sqlsrv_connect')) { $this->errorNum = 1; $this->errorMsg = 'You do not have the sqlsrv extension installed on this server'; return; } // Attempt to connect to the server. if (!($this->connection = @sqlsrv_connect($this->host, $config))) { $this->errorNum = 2; $this->errorMsg = 'Can not connect to Microsoft SQL Server'; return; } // Make sure that DB warnings are not returned as errors. sqlsrv_configure('WarningsReturnAsErrors', 0); // If auto-select is enabled select the given database. if ($this->selectDatabase && !empty($this->_database)) { $this->select($this->_database); } }
/** * Connects to the database specified, if no connection exists * * This method is only intended to force a connection, all operations that * require a database connection will automatically call this method. * * @throws fAuthorizationException When the username and password are not accepted * * @return void */ public function connect() { // Don't try to reconnect if we are already connected if ($this->connection) { return; } $connection_error = FALSE; $authentication_error = FALSE; $database_error = FALSE; $errors = NULL; // Establish a connection to the database if ($this->extension == 'pdo') { $username = $this->username; $password = $this->password; $options = array(); if ($this->timeout !== NULL && $this->type != 'sqlite' && $this->type != 'mssql') { $options[PDO::ATTR_TIMEOUT] = $this->timeout; } if ($this->type == 'db2') { if ($this->host === NULL && $this->port === NULL) { $dsn = 'ibm:DSN:' . $this->database; } else { $dsn = 'ibm:DRIVER={IBM DB2 ODBC DRIVER};DATABASE=' . $this->database . ';HOSTNAME=' . $this->host . ';'; $dsn .= 'PORT=' . ($this->port ? $this->port : 60000) . ';'; $dsn .= 'PROTOCOL=TCPIP;UID=' . $username . ';PWD=' . $password . ';'; if ($this->timeout !== NULL) { $dsn .= 'CONNECTTIMEOUT=' . $this->timeout . ';'; } $username = NULL; $password = NULL; } } elseif ($this->type == 'mssql') { $separator = fCore::checkOS('windows') ? ',' : ':'; $port = $this->port ? $separator . $this->port : ''; $driver = fCore::checkOs('windows') ? 'mssql' : 'dblib'; $dsn = $driver . ':host=' . $this->host . $port . ';dbname=' . $this->database; // This driver does not support timeouts so we fake it here if ($this->timeout !== NULL) { fCore::startErrorCapture(); $resource = fsockopen($this->host, $this->port ? $this->port : 1433, $errno, $errstr, $this->timeout); $errors = fCore::stopErrorCapture(); if ($resource !== FALSE) { fclose($resource); } } } elseif ($this->type == 'mysql') { if (substr($this->host, 0, 5) == 'sock:') { $dsn = 'mysql:unix_socket=' . substr($this->host, 5) . ';dbname=' . $this->database; } else { $port = $this->port ? ';port=' . $this->port : ''; $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->database . $port; } } elseif ($this->type == 'oracle') { $port = $this->port ? ':' . $this->port : ''; $dsn = 'oci:dbname=' . $this->host . $port . '/' . $this->database . ';charset=AL32UTF8'; // This driver does not support timeouts so we fake it here if ($this->timeout !== NULL) { fCore::startErrorCapture(); $resource = fsockopen($this->host, $this->port ? $this->port : 1521, $errno, $errstr, $this->timeout); $errors = fCore::stopErrorCapture(); if ($resource !== FALSE) { fclose($resource); } } } elseif ($this->type == 'postgresql') { $dsn = 'pgsql:dbname=' . $this->database; if ($this->host && $this->host != 'sock:') { $dsn .= ' host=' . $this->host; } if ($this->port) { $dsn .= ' port=' . $this->port; } } elseif ($this->type == 'sqlite') { $dsn = 'sqlite:' . $this->database; } try { if ($errors) { $this->connection = FALSE; } else { $this->connection = new PDO($dsn, $username, $password, $options); if ($this->type == 'mysql') { $this->connection->setAttribute(PDO::MYSQL_ATTR_DIRECT_QUERY, 1); } } } catch (PDOException $e) { $this->connection = FALSE; $errors = $e->getMessage(); } } if ($this->extension == 'sqlite') { $this->connection = sqlite_open($this->database); } if ($this->extension == 'ibm_db2') { $username = $this->username; $password = $this->password; if ($this->host === NULL && $this->port === NULL && $this->timeout === NULL) { $connection_string = $this->database; } else { $connection_string = 'DATABASE=' . $this->database . ';HOSTNAME=' . $this->host . ';'; $connection_string .= 'PORT=' . ($this->port ? $this->port : 60000) . ';'; $connection_string .= 'PROTOCOL=TCPIP;UID=' . $this->username . ';PWD=' . $this->password . ';'; if ($this->timeout !== NULL) { $connection_string .= 'CONNECTTIMEOUT=' . $this->timeout . ';'; } $username = NULL; $password = NULL; } $options = array('autocommit' => DB2_AUTOCOMMIT_ON, 'DB2_ATTR_CASE' => DB2_CASE_LOWER); $this->connection = db2_connect($connection_string, $username, $password, $options); if ($this->connection === FALSE) { $errors = db2_conn_errormsg(); } } if ($this->extension == 'mssql') { if ($this->timeout !== NULL) { $old_timeout = ini_get('mssql.connect_timeout'); ini_set('mssql.connect_timeout', $this->timeout); } fCore::startErrorCapture(); $separator = fCore::checkOS('windows') ? ',' : ':'; $this->connection = mssql_connect($this->port ? $this->host . $separator . $this->port : $this->host, $this->username, $this->password, TRUE); if ($this->connection !== FALSE && mssql_select_db($this->database, $this->connection) === FALSE) { $this->connection = FALSE; } $errors = fCore::stopErrorCapture(); if ($this->timeout !== NULL) { ini_set('mssql.connect_timeout', $old_timeout); } } if ($this->extension == 'mysql') { if ($this->timeout !== NULL) { $old_timeout = ini_get('mysql.connect_timeout'); ini_set('mysql.connect_timeout', $this->timeout); } if (substr($this->host, 0, 5) == 'sock:') { $host = substr($this->host, 4); } elseif ($this->port) { $host = $this->host . ':' . $this->port; } else { $host = $this->host; } fCore::startErrorCapture(); $this->connection = mysql_connect($host, $this->username, $this->password, TRUE); $errors = fCore::stopErrorCapture(); if ($this->connection !== FALSE && mysql_select_db($this->database, $this->connection) === FALSE) { $errors = 'Unknown database'; $this->connection = FALSE; } if ($this->connection && function_exists('mysql_set_charset') && !mysql_set_charset('utf8', $this->connection)) { throw new fConnectivityException('There was an error setting the database connection to use UTF-8'); } if ($this->timeout !== NULL) { ini_set('mysql.connect_timeout', $old_timeout); } } if ($this->extension == 'mysqli') { $this->connection = mysqli_init(); if ($this->timeout !== NULL) { mysqli_options($this->connection, MYSQLI_OPT_CONNECT_TIMEOUT, $this->timeout); } fCore::startErrorCapture(); if (substr($this->host, 0, 5) == 'sock:') { $result = mysqli_real_connect($this->connection, 'localhost', $this->username, $this->password, $this->database, $this->port, substr($this->host, 5)); } elseif ($this->port) { $result = mysqli_real_connect($this->connection, $this->host, $this->username, $this->password, $this->database, $this->port); } else { $result = mysqli_real_connect($this->connection, $this->host, $this->username, $this->password, $this->database); } if (!$result) { $this->connection = FALSE; } $errors = fCore::stopErrorCapture(); if ($this->connection && function_exists('mysqli_set_charset') && !mysqli_set_charset($this->connection, 'utf8')) { throw new fConnectivityException('There was an error setting the database connection to use UTF-8'); } } if ($this->extension == 'oci8') { fCore::startErrorCapture(); $resource = TRUE; // This driver does not support timeouts so we fake it here if ($this->timeout !== NULL) { $resource = fsockopen($this->host, $this->port ? $this->port : 1521, $errno, $errstr, $this->timeout); if ($resource !== FALSE) { fclose($resource); $resource = TRUE; } else { $this->connection = FALSE; } } if ($resource) { $this->connection = oci_connect($this->username, $this->password, $this->host . ($this->port ? ':' . $this->port : '') . '/' . $this->database, 'AL32UTF8'); } $errors = fCore::stopErrorCapture(); } if ($this->extension == 'pgsql') { $connection_string = "dbname='" . addslashes($this->database) . "'"; if ($this->host && $this->host != 'sock:') { $connection_string .= " host='" . addslashes($this->host) . "'"; } if ($this->username) { $connection_string .= " user='******'"; } if ($this->password) { $connection_string .= " password='******'"; } if ($this->port) { $connection_string .= " port='" . $this->port . "'"; } if ($this->timeout !== NULL) { $connection_string .= " connect_timeout='" . $this->timeout . "'"; } fCore::startErrorCapture(); $this->connection = pg_connect($connection_string, PGSQL_CONNECT_FORCE_NEW); $errors = fCore::stopErrorCapture(); } if ($this->extension == 'sqlsrv') { $options = array('Database' => $this->database); if ($this->username !== NULL) { $options['UID'] = $this->username; } if ($this->password !== NULL) { $options['PWD'] = $this->password; } if ($this->timeout !== NULL) { $options['LoginTimeout'] = $this->timeout; } $this->connection = sqlsrv_connect($this->host . ',' . $this->port, $options); if ($this->connection === FALSE) { $errors = sqlsrv_errors(); } sqlsrv_configure('WarningsReturnAsErrors', 0); } // Ensure the connection was established if ($this->connection === FALSE) { $this->handleConnectionErrors($errors); } // Make MySQL act more strict and use UTF-8 if ($this->type == 'mysql') { $this->execute("SET SQL_MODE = 'REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE'"); $this->execute("SET NAMES 'utf8'"); $this->execute("SET CHARACTER SET utf8"); } // Make SQLite behave like other DBs for assoc arrays if ($this->type == 'sqlite') { $this->execute('PRAGMA short_column_names = 1'); } // Fix some issues with mssql if ($this->type == 'mssql') { if (!isset($this->schema_info['character_set'])) { $this->determineCharacterSet(); } $this->execute('SET TEXTSIZE 65536'); $this->execute('SET QUOTED_IDENTIFIER ON'); } // Make PostgreSQL use UTF-8 if ($this->type == 'postgresql') { $this->execute("SET NAMES 'UTF8'"); } // Oracle has different date and timestamp defaults if ($this->type == 'oracle') { $this->execute("ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD'"); $this->execute("ALTER SESSION SET NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS'"); $this->execute("ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT = 'YYYY-MM-DD HH24:MI:SS TZR'"); $this->execute("ALTER SESSION SET NLS_TIME_FORMAT = 'HH24:MI:SS'"); $this->execute("ALTER SESSION SET NLS_TIME_TZ_FORMAT = 'HH24:MI:SS TZR'"); } }
/** * Connects to the database if needed. * * @return void Returns void if the database connected successfully. * * @since 1.0 * @throws \RuntimeException */ public function connect() { if ($this->connection) { return; } // Build the connection configuration array. $config = array('Database' => $this->options['database'], 'uid' => $this->options['user'], 'pwd' => $this->options['password'], 'CharacterSet' => 'UTF-8', 'ReturnDatesAsStrings' => true); // Make sure the SQLSRV extension for PHP is installed and enabled. if (!static::isSupported()) { throw new UnsupportedAdapterException('PHP extension sqlsrv_connect is not available.'); } // Attempt to connect to the server. if (!($this->connection = @sqlsrv_connect($this->options['host'], $config))) { $this->log(Log\LogLevel::ERROR, 'Could not connect to SQL Server', array('errors' => sqlsrv_errors())); throw new ConnectionFailureException('Could not connect to SQL Server'); } // Make sure that DB warnings are not returned as errors. sqlsrv_configure('WarningsReturnAsErrors', 0); // If auto-select is enabled select the given database. if ($this->options['select'] && !empty($this->options['database'])) { $this->select($this->options['database']); } }
/** * @see DBManager::query() */ public function query($sql, $dieOnError = false, $msg = '', $suppress = false) { global $app_strings; $sql = $this->_appendN($sql); $this->countQuery($sql); $GLOBALS['log']->info('Query:' . $sql); $this->checkConnection(); $this->query_time = microtime(true); if ($suppress) { } else { $result = @sqlsrv_query($this->database, $sql); } if (!$result) { // awu Bug 10657: ignoring mssql error message 'Changed database context to' - an intermittent // and difficult to reproduce error. The message is only a warning, and does // not affect the functionality of the query $sqlmsg = $this->_getLastErrorMessages(); $sqlpos = strpos($sqlmsg, 'Changed database context to'); $sqlpos2 = strpos($sqlmsg, 'Warning:'); $sqlpos3 = strpos($sqlmsg, 'Checking identity information:'); if ($sqlpos !== false || $sqlpos2 !== false || $sqlpos3 !== false) { // if sqlmsg has 'Changed database context to', just log it $GLOBALS['log']->debug($sqlmsg . ": " . $sql); } else { $GLOBALS['log']->fatal($sqlmsg . ": " . $sql); if ($dieOnError) { sugar_die('SQL Error : ' . $sqlmsg); } else { echo 'SQL Error : ' . $sqlmsg; } } } $this->lastmysqlrow = -1; $this->query_time = microtime(true) - $this->query_time; $GLOBALS['log']->info('Query Execution Time:' . $this->query_time); $this->checkError($msg . ' Query Failed:' . $sql . '::', $dieOnError); //suppress non error messages sqlsrv_configure('WarningsReturnAsErrors', false); return $result; }
public function Connect() { // Lookup Adapter-Specific Connection Properties $strServer = $this->Server; $strName = $this->Database; $strUsername = $this->Username; $strPassword = $this->Password; $strPort = $this->Port; if ($strPort) { // Windows Servers if (array_key_exists('OS', $_SERVER) && stristr($_SERVER['OS'], 'Win') !== false) { $strServer .= ',' . $strPort; } else { $strServer .= ':' . $strPort; } } // define the characterset for the sqlsrv driver // special handling for utf-8 data $strCharacterset = QApplication::$EncodingType == 'UTF-8' ? 'UTF-8' : 'SQLSRV_ENC_CHAR'; // Connect to the Database Server // Disable warnings as errors behavior sqlsrv_configure("WarningsReturnAsErrors", 0); // Set connection parameters $strConnectionInfoArray = array('UID' => $strUsername, 'PWD' => $strPassword, 'Database' => $strName, 'CharacterSet' => $strCharacterset); // Connect using SQL Server Authentication $this->objSqlSrvConn = sqlsrv_connect($strServer, $strConnectionInfoArray); if ($this->objSqlSrvConn === false) { // Determine the errorinformation $this->GetErrorInformation($strErrorinformation, $strErrorCode); $objException = new QSqlServer2005DatabaseException('Unable to connect: ' . $strErrorinformation, $strErrorCode, null); $objException->IncrementOffset(); throw $objException; } // Update Connected Flag $this->blnConnectedFlag = true; }
/** * SQLSRV DBO driver constructor; sets SQL Server error reporting defaults * * @param array $config Configuration data from app/config/databases.php * @return boolean True if connected successfully, false on error */ function __construct($config, $autoConnect = true) { if ($autoConnect) { if (!function_exists('sqlsrv_configure')) { trigger_error(__("PHP SQL Server interface is not installed, cannot continue. For troubleshooting information, see http://msdn.microsoft.com/en-us/library/ee229551(v=SQL.10).aspx", true), E_USER_WARNING); } sqlsrv_configure('LogSeverity', 1); } return parent::__construct($config, $autoConnect); }
<?php sqlsrv_configure('WarningsReturnAsErrors', false); print_r("calling connect", true); $c = sqlsrv_connect('(local)', array('Database' => 'master')); if ($c === false) { die(print_r(sqlsrv_errors(), true)); } echo "Connected!\n"; $s = sqlsrv_query($c, 'drop table [php_table_1_WREADHYPERV]'); $s = sqlsrv_query($c, 'create table [php_table_1_WREADHYPERV] ([γεια σας κόσμο] [nvarchar](100) NOT NULL, [col2] [nvarchar](100) NOT NULL, [col3] [nvarchar](100) NOT NULL)'); if ($s === false) { die(print_r(sqlsrv_errors(), true)); } $stmt = sqlsrv_query($c, 'SELECT * FROM [php_table_1_WREADHYPERV]'); if ($stmt === false) { die(print_r(sqlsrv_errors(), true)); } $ct = 1; do { if (sqlsrv_num_fields($stmt) > 0) { $meta = sqlsrv_field_metadata($stmt); foreach ($meta as &$col) { $col['BinaryName'] = '0x' . bin2hex($col['Name']); } echo "Result {$ct} Meta Data:\r\n" . print_r($meta, true); $ctr = 0; while ($row = sqlsrv_fetch_array($stmt)) { ++$ctr;
/** * @depends testInit */ public function testConfigure($init) { echo "\nConfigure function test.\n"; // TODO: change to NOT test for default values $this->assertTrue(sqlsrv_configure('ClientBufferMaxKBSize', 10240)); $this->assertTrue(sqlsrv_configure('LogSeverity', SQLSRV_LOG_SEVERITY_ERROR)); $this->assertTrue(sqlsrv_configure('LogSubsystems', SQLSRV_LOG_SYSTEM_OFF)); $this->assertTrue(sqlsrv_configure('WarningsReturnAsErrors', true)); $this->assertTrue(sqlsrv_get_config('ClientBufferMaxKBSize') == 10240); $this->assertTrue(sqlsrv_get_config('LogSeverity') == SQLSRV_LOG_SEVERITY_ERROR); $this->assertTrue(sqlsrv_get_config('LogSubsystems') == SQLSRV_LOG_SYSTEM_OFF); $this->assertTrue(sqlsrv_get_config('WarningsReturnAsErrors') == true); }
/** * Connect to and select database * * @since 3.0.0 */ function db_connect() { /* Specify the server and connection string attributes. */ $connection_info = array('Database' => $this->dbname, 'CharacterSet' => 'UTF-8', 'ReturnDatesAsStrings' => true); // Add username and password if set, not setting them uses windows authentication if (!empty($this->dbuser) && !empty($this->dbpassword)) { $connection_info['UID'] = $this->dbuser; $connection_info['PWD'] = $this->dbpassword; } // Is this SQL Azure? if (stristr($this->dbhost, 'database.windows.net') !== false) { // Need to turn off MultipleActiveResultSets, this requires // Sql Server Driver for PHP 1.1 (1.0 doesn't support this property) $connection_info['MultipleActiveResultSets'] = false; $this->azure = true; } $this->dbh = sqlsrv_connect($this->dbhost, $connection_info); // we're going to be noisy if debug is on and we fail if (!$this->dbh && WP_DEBUG) { $error = sqlsrv_errors(SQLSRV_ERR_ALL); if (is_array($error)) { trigger_error('SQLSTATE: ' . $error['SQLSTATE'] . ' - ' . $error['message']); } } sqlsrv_configure('WarningsReturnAsErrors', WP_DEBUG); // we're going to be noisy if debug is on if (!$this->dbh) { $this->bail(sprintf("\n<h1>Error establishing a database connection</h1>\n<p>This either means that the username and password information in your <code>wp-config.php</code> file is incorrect or we can't contact the database server at <code>%s</code>. This could mean your host's database server is down.</p>\n<ul>\n <li>Are you sure you have the correct username and password?</li>\n <li>Are you sure that you have typed the correct hostname?</li>\n <li>Are you sure that the database server is running?</li>\n</ul>\n<p>If you're unsure what these terms mean you should probably contact your host. If you still need help you can always visit the <a href='http://wordpress.org/support/'>WordPress Support Forums</a>.</p>\n", $this->dbhost), 'db_connect_fail'); return; } // Make sure textsize fields are set to max. @sqlsrv_query('SET TEXTSIZE 2147483647'); $this->ready = true; }
/** * Connects to the database if needed. * * @return void Returns void if the database connected successfully. * * @since 12.1 * @throws RuntimeException */ public function connect() { if ($this->connection) { return; } // Build the connection configuration array. $config = array('Database' => $this->options['database'], 'uid' => $this->options['user'], 'pwd' => $this->options['password'], 'CharacterSet' => 'UTF-8', 'ReturnDatesAsStrings' => true); // Make sure the SQLSRV extension for PHP is installed and enabled. if (!function_exists('sqlsrv_connect')) { throw new RuntimeException('PHP extension sqlsrv_connect is not available.'); } // Attempt to connect to the server. if (!($this->connection = @sqlsrv_connect($this->options['host'], $config))) { throw new RuntimeException('Database sqlsrv_connect failed'); } // Make sure that DB warnings are not returned as errors. sqlsrv_configure('WarningsReturnAsErrors', 0); // If auto-select is enabled select the given database. if ($this->options['select'] && !empty($this->options['database'])) { $this->select($this->options['database']); } // Set charactersets. $this->utf = $this->setUtf(); }
/** * @see DBManager::query() */ public function query($sql, $dieOnError = false, $msg = '', $suppress = false, $keepResult = false) { if (is_array($sql)) { return $this->queryArray($sql, $dieOnError, $msg, $suppress); } $sql = $this->_appendN($sql); $this->countQuery($sql); $GLOBALS['log']->info('Query:' . $sql); $this->checkConnection(); $this->query_time = microtime(true); $result = $suppress ? @sqlsrv_query($this->database, $sql) : sqlsrv_query($this->database, $sql); $this->query_time = microtime(true) - $this->query_time; $GLOBALS['log']->info('Query Execution Time:' . $this->query_time); $this->checkError($msg . ' Query Failed:' . $sql . '::', $dieOnError); //suppress non error messages sqlsrv_configure('WarningsReturnAsErrors', false); return $result; }
function __construct() { if ($this->debug) { ADOConnection::outp("<pre>"); sqlsrv_set_error_handling(SQLSRV_ERRORS_LOG_ALL); sqlsrv_log_set_severity(SQLSRV_LOG_SEVERITY_ALL); sqlsrv_log_set_subsystems(SQLSRV_LOG_SYSTEM_ALL); sqlsrv_configure('WarningsReturnAsErrors', 0); } else { sqlsrv_set_error_handling(0); sqlsrv_log_set_severity(0); sqlsrv_log_set_subsystems(SQLSRV_LOG_SYSTEM_ALL); sqlsrv_configure('WarningsReturnAsErrors', 0); } }
//echo "* ---End of result --- *\r\n"; } while (sqlsrv_next_result($stmt)); sqlsrv_free_stmt($stmt); } } sqlsrv_configure("WarningsReturnAsErrors", 1); sqlsrv_close($conn); } catch (PDOException $e) { $statusCode = 1; $statusMessage = 'RestoreDatabase SQLError: ' . $e->getMessage(); $log->add_log($sessionID, 'Error', $statusMessage); echo "Error: " . $e->getMessage(); sqlsrv_configure("WarningsReturnAsErrors", 1); sqlsrv_close($conn); } catch (Exception $e) { $statusCode = $e->getCode(); $statusMessage = 'RestoreDatabase Error: ' . $e->getMessage(); if (!$log->add_log($sessionID, 'Error', $statusMessage, "N/A", true)) { $statusMessage = $statusMessage . " **Logging Failed**"; } echo "Error: " . $e->getMessage(); sqlsrv_configure("WarningsReturnAsErrors", 1); sqlsrv_close($conn); } if ($statusCode == 0) { $statusMessage = 'Database restore successful.'; $log->add_log($sessionID, 'Info', $statusMessage); $statusArray[0] = $statusCode; $statusArray[1] = $statusMessage; $IMSBase->GenerateXMLResponse($sessionID, $statusArray, NULL, $dataArray, "BACKUP", "BACKUP_ENTRY"); }
function ADODB_mssqlnative() { if ($this->debug) { error_log("<pre>"); sqlsrv_set_error_handling(SQLSRV_ERRORS_LOG_ALL); sqlsrv_log_set_severity(SQLSRV_LOG_SEVERITY_ALL); sqlsrv_log_set_subsystems(SQLSRV_LOG_SYSTEM_ALL); sqlsrv_configure('warnings_return_as_errors', 0); } else { sqlsrv_set_error_handling(0); sqlsrv_log_set_severity(0); sqlsrv_log_set_subsystems(SQLSRV_LOG_SYSTEM_ALL); sqlsrv_configure('warnings_return_as_errors', 0); } }
/** * Connect to the database. * * @throws <b>AgaviDatabaseException</b> If a connection could not be * created. * * @author David Zülke <*****@*****.**> * @since 1.0.4 */ protected function connect() { $serverName = $this->getParameter('server_name'); if ($serverName == null) { // missing required server_name parameter $error = 'Database configuration is missing "server_name" parameter'; throw new AgaviDatabaseException($error); } if ($this->hasParameter('settings')) { foreach ((array) $this->getParameter('settings') as $key => $value) { if (!sqlsrv_configure($key, is_string($value) && strpos($value, 'SQLSRV_') === 0 && defined($value) ? constant($value) : (is_numeric($value) ? (int) $value : $value))) { throw new AgaviDatabaseException(sprintf('Unsupported key or value for setting "%s".', $key)); } } } $connectionInfo = $this->getParameter('connection_info'); foreach ($connectionInfo as &$value) { $value = is_string($value) && strpos($value, 'SQLSRV_') === 0 && defined($value) ? constant($value) : (is_numeric($value) ? (int) $value : $value); } $this->connection = sqlsrv_connect($serverName, $connectionInfo); if (!$this->connection) { $this->connection = null; throw new AgaviDatabaseException(sprintf("%s\n\n%s", sprintf('Could not open database connection "%s".', $this->getName()), implode("\n", $this->getErrors()))); } $this->resource =& $this->connection; foreach ((array) $this->getParameter('init_queries') as $query) { sqlsrv_query($this->connection, $query); } }