Example #1
0
 /**
  * Create the class instance
  */
 public function __construct()
 {
     static::$link = mysqli_init();
     static::$link->real_connect(static::$host, static::$username, static::$password, static::$dbname);
     static::$inits++;
     static::$instance = $this;
 }
Example #2
0
	/**
	 * Create a new connection to a mysql server.
	 *
	 * @param string $host
	 * @param string $user
	 * @param string $pass
	 * @param string $database
	 *
	 * @throws \DMI_Authentication_Exception
	 * @throws \DMI_ServerNotFound_Exception
	 * @throws \DMI_Exception
	 *
	 * @return mixed|void
	 */
	public function connect($host, $user, $pass, $database){

		// Did the host come in with a port attached?
		if(strpos($host, ':') !== false) list($host, $port) = explode(':', $host);
		else $port = 3306;

		if(!class_exists('mysqli', false)){
			throw new \DMI_Exception('Unable to locate the PHP MySQLi library.  Please switch to a supported driver or see http://us3.php.net/manual/en/book.mysqli.php for more information.');
		}

		$this->_conn = new \mysqli();

		// Errors, SHHH!  I'll handle them manually!
		@$this->_conn->real_connect($host, $user, $pass, $database, $port);

		// Setting the correct exception would be useful!
		switch($this->_conn->errno){
			// Server not found
			case 2002:
				throw new \DMI_ServerNotFound_Exception($this->_conn->error, $this->_conn->errno);
			// User not allowed
			case 1045:
				throw new \DMI_Authentication_Exception($this->_conn->error, $this->_conn->errno);
			// No error, just break;
			case 0:
				break;
			// Everything else gets a generic error.
			default:
				throw new \DMI_Exception($this->_conn->error, $this->_conn->errno);
		}

		// Set the encoding to UTF-8
		// This will prevent the mysql server from translating characters to their LATIN versions during the commit.
		$this->_conn->query("SET NAMES utf8");
	}
Example #3
0
 /**
  * @param array  $params
  * @param string $username
  * @param string $password
  * @param array  $driverOptions
  *
  * @throws \Doctrine\DBAL\Driver\Mysqli\MysqliException
  */
 public function __construct(array $params, $username, $password, array $driverOptions = array())
 {
     $port = isset($params['port']) ? $params['port'] : ini_get('mysqli.default_port');
     // Fallback to default MySQL port if not given.
     if (!$port) {
         $port = 3306;
     }
     $socket = isset($params['unix_socket']) ? $params['unix_socket'] : ini_get('mysqli.default_socket');
     $dbname = isset($params['dbname']) ? $params['dbname'] : null;
     $flags = isset($driverOptions[static::OPTION_FLAGS]) ? $driverOptions[static::OPTION_FLAGS] : null;
     $this->_conn = mysqli_init();
     $this->setDriverOptions($driverOptions);
     $previousHandler = set_error_handler(function () {
     });
     if (!$this->_conn->real_connect($params['host'], $username, $password, $dbname, $port, $socket, $flags)) {
         set_error_handler($previousHandler);
         $sqlState = 'HY000';
         if (@$this->_conn->sqlstate) {
             $sqlState = $this->_conn->sqlstate;
         }
         throw new MysqliException($this->_conn->connect_error, $sqlState, $this->_conn->connect_errno);
     }
     set_error_handler($previousHandler);
     if (isset($params['charset'])) {
         $this->_conn->set_charset($params['charset']);
     }
 }
 public function __construct()
 {
     $this->loadConfiguration();
     $this->mysqli = mysqli_init();
     if (!$this->mysqli->real_connect($GLOBALS['sys_dbhost'], $GLOBALS['sys_dbuser'], $GLOBALS['sys_dbpasswd'])) {
         $this->mysqli = false;
     }
 }
Example #5
0
 /**
  * Establishes db connection
  */
 private function connect($host, $user, $pwd, $dbname)
 {
     $this->database = mysqli_init();
     $this->database->real_connect($host, $user, $pwd, $dbname);
     if ($this->database === NULL || $this->database->connect_errno) {
         die("Failed to connect to database!");
     }
     $this->database->set_charset("utf8");
 }
 public function __construct(array $params, $username, $password, array $driverOptions = array())
 {
     $port = isset($params['port']) ? $params['port'] : ini_get('mysqli.default_port');
     $socket = isset($params['unix_socket']) ? $params['unix_socket'] : ini_get('mysqli.default_socket');
     $this->_conn = mysqli_init();
     if (!$this->_conn->real_connect($params['host'], $username, $password, $params['dbname'], $port, $socket)) {
         throw new MysqliException($this->_conn->connect_error, $this->_conn->connect_errno);
     }
     if (isset($params['charset'])) {
         $this->_conn->set_charset($params['charset']);
     }
 }
 public function open()
 {
     if ($this->connected) {
         return false;
     }
     $this->mysqli = mysqli_init();
     $this->connected = @$this->mysqli->real_connect($this->settings->getHost(), $this->settings->getUsername(), $this->settings->getPassword(), $this->settings->getSchema());
     if (!$this->connected) {
         throw new ConnectionException(sprintf('Unable to connect to host "%s" as user "%s". %s.', $this->settings->getHost(), $this->settings->getUsername(), mysqli_connect_error()), '', mysqli_connect_errno());
     }
     @$this->mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);
     @$this->mysqli->set_charset($this->settings->getCharset());
     return true;
 }
 /**
  * Connect to the database server and select the database
  *
  * @throws \Exception If the connection cannot be established
  */
 protected function connect()
 {
     $host = $this->arrConfig['dbHost'];
     if ($this->arrConfig['dbPconnect']) {
         $host = 'p:' . $host;
     }
     $this->resConnection = mysqli_init();
     $this->resConnection->options(MYSQLI_INIT_COMMAND, "SET sql_mode='" . $this->arrConfig['dbSqlMode'] . "'");
     $this->resConnection->real_connect($host, $this->arrConfig['dbUser'], $this->arrConfig['dbPass'], $this->arrConfig['dbDatabase'], $this->arrConfig['dbPort'], $this->arrConfig['dbSocket']);
     if ($this->resConnection->connect_error) {
         throw new \Exception($this->resConnection->connect_error);
     }
     $this->resConnection->set_charset($this->arrConfig['dbCharset']);
 }
Example #9
0
 /**
  * {@inheritDoc}
  */
 protected function realConnect(array $parameters)
 {
     // init
     $this->link = new \mysqli();
     $this->link->init();
     // set driver specific options
     if (!empty($parameters['options'])) {
         foreach ($parameters['options'] as $option => $value) {
             $option = strtoupper($option);
             $this->attributes[$option] = $value;
         }
     }
     foreach ($this->attributes as $attr => $value) {
         if (is_string($attr)) {
             $option = constant($attr);
             if (defined($option)) {
                 $this->link->options($option, $value);
             }
         } else {
             $this->link->options($attr, $value);
         }
     }
     // real connect
     $this->link->real_connect(isset($parameters['host']) ? $parameters['host'] : 'localhost', isset($parameters['username']) ? $parameters['username'] : '******', isset($parameters['password']) ? $parameters['password'] : null, isset($parameters['db']) ? $parameters['db'] : null, isset($parameters['port']) ? (int) $parameters['port'] : null, isset($parameters['socket']) ? $parameters['socket'] : null);
     if ($this->link->connect_error) {
         throw new LogicException(Message::get(Message::DB_CONNECT_FAIL, $this->link->connect_errno, $this->link->connect_error), Message::DB_CONNECT_FAIL);
     }
     // set charset
     if (!empty($parameters['charset'])) {
         $this->link->set_charset($parameters['charset']);
     }
     return $this;
 }
Example #10
0
 /**
  * Connect to db, return connect identifier
  *
  * @param string $dbhost, The MySQL server hostname.
  * @param string $dbuser, The username.
  * @param string $dbpass, The password.
  * @param string $dbname, The db name, optional, defualt to ''
  * @param string $dbport, The MySQL server port, optional, defualt to '3306'
  * @param string $charset, Connect charset, optional, default to 'utf8'
  * @param bool $pconnect, Whether persistent connection: 1 - Yes, 0 - No
  * @return link_identifier
  */
 function connect($dbhost, $dbuser, $dbpass, $dbname = '', $dbport = '3306', $charset = 'utf8', $pconnect = 0)
 {
     if ($pconnect && version_compare(PHP_VERSION, '5.3.0', '>=')) {
         //PHP since 5.3.0 added the ability of persistent connections.
         $dbhost = 'p:' . $dbhost;
     }
     //$mysqli = mysqli_init();
     $mysqli = new mysqli();
     if (!$mysqli) {
         $this->halt('mysqli_init failed');
     }
     //$mysqli->options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0');
     $mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, $this->connTimeout);
     // - TRUE makes mysql_connect() always open a new link, even if
     //   mysql_connect() was called before with the same parameters.
     //   This is important if you are using two databases on the same
     //   server.
     // - 2 means CLIENT_FOUND_ROWS: return the number of found
     //   (matched) rows, not the number of affected rows.
     if (!@$mysqli->real_connect($dbhost, $dbuser, $dbpass, $dbname, $dbport, null, MYSQLI_CLIENT_COMPRESS | MYSQLI_CLIENT_FOUND_ROWS)) {
         $this->halt("Connect to {$dbuser}@{$dbhost}:{$dbport} Error: ({$mysqli->connect_errno}){$mysqli->connect_error}");
     }
     $mysqli->set_charset($charset);
     $this->linkId = $mysqli;
     return $this->linkId;
 }
Example #11
0
 /**
  * Creates a real connection to the database with multi-query capability.
  *
  * @return void
  * @throws Zend_Db_Adapter_Mysqli_Exception
  */
 protected function _connect()
 {
     if ($this->_connection) {
         return;
     }
     if (!extension_loaded('mysqli')) {
         throw new Zend_Db_Adapter_Exception('mysqli extension is not installed');
     }
     // Suppress connection warnings here.
     // Throw an exception instead.
     @($conn = new mysqli());
     if (false === $conn || mysqli_connect_errno()) {
         throw new Zend_Db_Adapter_Mysqli_Exception(mysqli_connect_errno());
     }
     $conn->init();
     $conn->options(MYSQLI_OPT_LOCAL_INFILE, true);
     #$conn->options(MYSQLI_CLIENT_MULTI_QUERIES, true);
     $port = !empty($this->_config['port']) ? $this->_config['port'] : null;
     $socket = !empty($this->_config['unix_socket']) ? $this->_config['unix_socket'] : null;
     // socket specified in host config
     if (strpos($this->_config['host'], '/') !== false) {
         $socket = $this->_config['host'];
         $this->_config['host'] = null;
     } elseif (strpos($this->_config['host'], ':') !== false) {
         list($this->_config['host'], $port) = explode(':', $this->_config['host']);
     }
     #echo "<pre>".print_r($this->_config,1)."</pre>"; die;
     @$conn->real_connect($this->_config['host'], $this->_config['username'], $this->_config['password'], $this->_config['dbname'], $port, $socket);
     if (mysqli_connect_errno()) {
         throw new Zend_Db_Adapter_Mysqli_Exception(mysqli_connect_error());
     }
     $this->_connection = $conn;
     /** @link http://bugs.mysql.com/bug.php?id=18551 */
     $this->_connection->query("SET SQL_MODE=''");
 }
Example #12
0
 /**
  * Connect to database
  * @return bool
  */
 public function connect($host, $user, $pass, $port = 3306, $options = array())
 {
     $client_flags = defined('MYSQL_CLIENT_FLAGS') ? MYSQL_CLIENT_FLAGS : 0;
     $this->dbh = mysqli_init();
     $socket = null;
     $port_or_socket = strstr($host, ':');
     if (!empty($port_or_socket)) {
         $host = substr($host, 0, strpos($host, ':'));
         $port_or_socket = substr($port_or_socket, 1);
         if (0 !== strpos($port_or_socket, '/')) {
             $port = intval($port_or_socket);
             $maybe_socket = strstr($port_or_socket, ':');
             if (!empty($maybe_socket)) {
                 $socket = substr($maybe_socket, 1);
             }
         } else {
             $socket = $port_or_socket;
             $port = null;
         }
     }
     if (WP_DEBUG) {
         $this->dbh->real_connect($host, $user, $pass, null, $port, $socket, $client_flags);
     } else {
         @$this->dbh->real_connect($host, $user, $pass, null, $port, $socket, $client_flags);
     }
     if (!empty($options['key']) && !empty($options['cert']) && !empty($options['ca'])) {
         $this->dbh->ssl_set($options['key'], $options['cert'], $options['ca'], $options['ca_path'], $options['cipher']);
     }
     return !mysqli_connect_error();
 }
 /**
  * Open a (persistent) connection to a MySQL server
  * mysql_pconnect() wrapper function
  * Method is taken from t3lib_db
  *
  * @param string Database host IP/domain
  * @param string Username to connect with.
  * @param string Password to connect with.
  */
 private function connect($credArr)
 {
     if (!extension_loaded('mysqli')) {
         throw new \RuntimeException('Database Error: PHP mysqli extension not loaded. This is a must have for TYPO3 CMS!', 1271492607);
     }
     $dbHost = $credArr['host'] ? $credArr['host'] : 'localhost';
     $dbUsername = $credArr['username'];
     $dbPassword = $credArr['password'];
     $dbPort = isset($credArr['port']) ? (int) $credArr['port'] : 3306;
     $dbSocket = empty($credArr['socket']) ? NULL : $credArr['socket'];
     $dbCompress = !empty($credArr['dbClientCompress']) && $dbHost != 'localhost' && $dbHost != '127.0.0.1';
     if (isset($credArr['no_pconnect']) && !$credArr['no_pconnect']) {
         $dbHost = 'p:' . $dbHost;
     }
     $this->db = mysqli_init();
     $connected = $this->db->real_connect($dbHost, $dbUsername, $dbPassword, NULL, $dbPort, $dbSocket, $dbCompress ? MYSQLI_CLIENT_COMPRESS : 0);
     if (!$connected) {
         $message = 'Database Error: Could not connect to MySQL server ' . $dbHost . ' with user ' . $dbUsername . ': ' . $this->sql_error();
         throw new RuntimeException($message, 1271492616);
     }
     $this->isConnected = TRUE;
     $connectionCharset = empty($credArr['connectionCharset']) ? 'utf8' : $credArr['connectionCharset'];
     $this->db->set_charset($connectionCharset);
     $setDBinit = tx_rnbase_util_Strings::trimExplode(LF, str_replace("' . LF . '", LF, $credArr['setDBinit']), TRUE);
     foreach ($setDBinit as $v) {
         if ($this->query($v) === FALSE) {
             // TODO: handler errors
         }
     }
 }
Example #14
0
 /**
  * Create a new Mysqli object.
  *
  * @param array $params
  * @return object
  */
 public function __construct($key)
 {
     mysqli_report(MYSQLI_REPORT_STRICT);
     $params = Config::get('mysql.' . $key);
     if ($params === null && IS_SUBSITE) {
         $params = MainConfig::get('mysql.' . $key);
     }
     if ($params === null) {
         $params = [];
     }
     parent::init();
     $params['pass'] = isset($params['pass']) ? $params['pass'] : '';
     $params['user'] = isset($params['user']) ? $params['user'] : '******';
     $params['host'] = isset($params['host']) ? $params['host'] : '127.0.0.1';
     $params['port'] = isset($params['port']) ? $params['port'] : 3306;
     $params['timeout'] = isset($params['timeout']) ? $params['timeout'] : 30;
     $params['charset'] = isset($params['charset']) ? $params['charset'] : 'utf8';
     $params['database'] = isset($params['database']) ? $params['database'] : false;
     parent::options(MYSQLI_OPT_CONNECT_TIMEOUT, $params['timeout']);
     parent::real_connect($params['host'], $params['user'], $params['pass'], $params['database'], $params['port']);
     if ($this->errno === 0) {
         $this->set_charset($params['charset']);
         if (isset($params['cache']) && $params['cache'] === false) {
             $this->cache(false);
         }
     }
 }
Example #15
0
 /**
  * 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;
     }
     /*
      * Unlike mysql_connect(), mysqli_connect() takes the port and socket as separate arguments. Therefore, we
      * have to extract them from the host string.
      */
     $port = isset($this->options['port']) ? $this->options['port'] : 3306;
     if (preg_match('/^(?P<host>((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(:(?P<port>.+))?$/', $this->options['host'], $matches)) {
         // It's an IPv4 address with or without port
         $this->options['host'] = $matches['host'];
         if (!empty($matches['port'])) {
             $port = $matches['port'];
         }
     } elseif (preg_match('/^(?P<host>\\[.*\\])(:(?P<port>.+))?$/', $this->options['host'], $matches)) {
         // We assume square-bracketed IPv6 address with or without port, e.g. [fe80:102::2%eth1]:3306
         $this->options['host'] = $matches['host'];
         if (!empty($matches['port'])) {
             $port = $matches['port'];
         }
     } elseif (preg_match('/^(?P<host>(\\w+:\\/{2,3})?[a-z0-9\\.\\-]+)(:(?P<port>[^:]+))?$/i', $this->options['host'], $matches)) {
         // Named host (e.g example.com or localhost) with or without port
         $this->options['host'] = $matches['host'];
         if (!empty($matches['port'])) {
             $port = $matches['port'];
         }
     } elseif (preg_match('/^:(?P<port>[^:]+)$/', $this->options['host'], $matches)) {
         // Empty host, just port, e.g. ':3306'
         $this->options['host'] = 'localhost';
         $port = $matches['port'];
     }
     // ... else we assume normal (naked) IPv6 address, so host and port stay as they are or default
     // Get the port number or socket name
     if (is_numeric($port)) {
         $this->options['port'] = (int) $port;
     } else {
         $this->options['socket'] = $port;
     }
     // Make sure the MySQLi extension for PHP is installed and enabled.
     if (!static::isSupported()) {
         throw new UnsupportedAdapterException('The MySQLi extension is not available');
     }
     $this->connection = mysqli_init();
     // Attempt to connect to the server.
     $connected = $this->connection->real_connect($this->options['host'], $this->options['user'], $this->options['password'], null, $this->options['port'], $this->options['socket']);
     if (!$connected) {
         $this->log(Log\LogLevel::ERROR, 'Could not connect to MySQL: ' . $this->connection->connect_error);
         throw new ConnectionFailureException('Could not connect to MySQL.', $this->connection->connect_errno);
     }
     // If auto-select is enabled select the given database.
     if ($this->options['select'] && !empty($this->options['database'])) {
         $this->select($this->options['database']);
     }
     $this->utf8mb4 = $this->serverClaimsUtf8mb4Support();
     // Set charactersets (needed for MySQL 4.1.2+).
     $this->utf = $this->setUtf();
 }
Example #16
0
 public function connect()
 {
     parent::real_connect($this->config['db_host'], $this->config['db_username'], $this->config['db_password']);
     if (!empty($this->current_database)) {
         parent::select_db($database_name);
     } else {
         parent::select_db($this->config['database']);
     }
 }
 /**
  * Constructor for the MySQLi Extension
  *
  * Throws an exception when connection fails
  *
  * @param $Host
  *   The hostname/ip address of the database server
  *
  * @param $Port
  *   The port on which the database server is listening
  *
  * @param $UserName
  *   A UserName which has access to the database we'll be using.
  *
  * @param $Password
  *   The Password for the UserName provided
  *
  * @param $Database
  *   The Database which contains the Neflaria tables
  *
  * @throws Exception
  */
 public function __construct($Host, $UserName, $Password, $Database, $Port)
 {
     parent::init();
     if (!parent::options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
         $this->LogError('?', 'Setting the connect timeout failed');
     }
     if (!parent::real_connect($Host, $UserName, $Password, $Database, $Port)) {
         $this->LogError(mysqli_connect_errno(), mysqli_connect_error());
     }
 }
Example #18
0
 /**
  * @param QuarkURI $uri
  *
  * @return mixed
  *
  * @throws QuarkArchException
  * @throws QuarkConnectionException
  */
 public function Connect(QuarkURI $uri)
 {
     $this->_connection = \mysqli_init();
     if (!$this->_connection) {
         throw new QuarkArchException('MySQLi initialization fault');
     }
     $options = $uri->options;
     if (is_array($options)) {
         foreach ($options as $key => $value) {
             if (!$this->_connection->options($key, $value)) {
                 throw new QuarkArchException('MySQLi option set error');
             }
         }
     }
     if (!$this->_connection->real_connect($uri->host, $uri->user, $uri->pass, QuarkSQL::DBName($uri->path), (int) $uri->port)) {
         throw new QuarkConnectionException($uri, Quark::LOG_FATAL);
     }
     $this->_sql = new QuarkSQL($this);
 }
Example #19
0
 public function __construct($host, $user, $pass, $db)
 {
     parent::init();
     if (!parent::real_connect($host, $user, $pass, $db)) {
         throw new Exception('ŠžŃˆŠøŠ±ŠŗŠ° ŠæŠ¾Š“ŠŗŠ»ŃŽŃ‡ŠµŠ½Šøя (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
     }
     if (!$this->set_charset('utf8')) {
         throw new Exception('ŠžŃˆŠøŠ±ŠŗŠ° ŠæрŠø Š·Š°Š³Ń€ŃƒŠ·ŠŗŠµ Š½Š°Š±Š¾Ń€Š° сŠøŠ¼Š²Š¾Š»Š¾Š² utf8: ' . $this->error);
     }
 }
Example #20
0
 public function __construct($host = '127.0.0.1', $username = '******', $password = '******', $dbname = 'web_train')
 {
     parent::init();
     if (!parent::options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
         die('Setting options failed');
     }
     if (!parent::real_connect($host, $username, $password, $dbname)) {
         die('Connect to db failed');
     }
     parent::query('set names utf8');
 }
Example #21
0
 /**
  * connect - Connects to mysql server
  *
  * @throws exception
  */
 public function connect()
 {
     if (!$this->connected) {
         parent::init();
         if (!parent::real_connect($this->host, $this->user, $this->pass, $this->db, $this->port)) {
             throw new Exception($this->connect_error);
         } else {
             $this->connected = true;
         }
     }
     return $this;
 }
 /**
  * @param array  $params
  * @param string $username
  * @param string $password
  * @param array  $driverOptions
  *
  * @throws \Doctrine\DBAL\Driver\Mysqli\MysqliException
  */
 public function __construct(array $params, $username, $password, array $driverOptions = array())
 {
     $port = isset($params['port']) ? $params['port'] : ini_get('mysqli.default_port');
     $socket = isset($params['unix_socket']) ? $params['unix_socket'] : ini_get('mysqli.default_socket');
     $this->_conn = mysqli_init();
     $this->setDriverOptions($driverOptions);
     $previousHandler = set_error_handler(function () {
     });
     if (!$this->_conn->real_connect($params['host'], $username, $password, $params['dbname'], $port, $socket)) {
         set_error_handler($previousHandler);
         $sqlState = 'HY000';
         if (@$this->_conn->sqlstate) {
             $sqlState = $this->_conn->sqlstate;
         }
         throw new MysqliException($this->_conn->connect_error, $sqlState, $this->_conn->connect_errno);
     }
     set_error_handler($previousHandler);
     if (isset($params['charset'])) {
         $this->_conn->set_charset($params['charset']);
     }
 }
Example #23
0
 private final function __construct()
 {
     parent::init();
     if (!parent::options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
         throw new Exception('Setting MYSQLI_INIT_COMMAND failed');
     }
     if (!parent::options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
         throw new Exception('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
     }
     if (!parent::real_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME)) {
         throw new Exception('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
     }
 }
Example #24
0
 public function rcon($host, $user, $pass, $db)
 {
     parent::init();
     if (!parent::options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
         die('Setting MYSQLI_INIT_COMMAND failed');
     }
     if (!parent::options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
         die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
     }
     #$db_connection = new mysqli('localhost', 'root', '', 'brechbuhler');
     if (!parent::real_connect($host, $user, $pass, $db)) {
         die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
     }
 }
Example #25
0
 function _dbconnect($dbhost, $dbuser, $dbpw, $dbcharset, $dbname, $pconnect, $halt = true)
 {
     $link = new mysqli();
     if (!$link->real_connect($dbhost, $dbuser, $dbpw, $dbname, null, null, MYSQLI_CLIENT_COMPRESS)) {
         $halt && $this->halt('notconnect', $this->errno());
     } else {
         $this->curlink = $link;
         if ($this->version() > '4.1') {
             $link->set_charset($dbcharset ? $dbcharset : $this->config[1]['dbcharset']);
             $serverset = $this->version() > '5.0.1' ? 'sql_mode=\'\'' : '';
             $serverset && $link->query("SET {$serverset}");
         }
     }
     return $link;
 }
 /**
  * Establish Database Connection
  *
  * @return void
  */
 public function connect()
 {
     // Check Active Connections (Only Connect Once)
     $key = $this->user . '@' . $this->db . '@' . $this->host;
     if (isset(self::$connections[$key])) {
         // Use Active Connection
         $this->connection = self::$connections[$key];
     } else {
         // Setup Connection
         $this->connection = mysqli_init();
         if (!$this->connection) {
             die(Log::halt('mysqli_init failed', 503));
         }
         // Set Database Timeout
         if (!$this->connection->options(MYSQLI_OPT_CONNECT_TIMEOUT, 10)) {
             die(Log::halt('Setting Options Failed', 503));
         }
         // Connect to Database
         if (!$this->connection->real_connect($this->host, $this->user, $this->pass, $this->db)) {
             die(Log::halt('Connect fatal error: could not connect to host - ' . mysqli_connect_error(), 503));
         }
         // UTF-8 Character Set
         if (!$this->connection->set_charset('utf8')) {
             die(Log::halt('Error loading character set utf8 - ' . $this->connection->error, 503));
         }
         // Set connection Timezone
         $timezone = @date_default_timezone_get();
         if (!$this->connection->query("SET time_zone = '" . $timezone . "';")) {
             die(Log::halt('Error setting timezone to ' . $timezone . ' - ' . $this->connection->error, 503));
         }
         // Debug Log: Connected to Database
         Log::db(__CLASS__, 'Connected To: ' . $this->db . '@' . $this->host);
         // Store Connection
         self::$connections[$key] = $this->connection;
     }
 }
Example #27
0
 /**
  * Constructor: Conecta a MySQL y establece el charset a utf8
  * @param string $host host de MySQL
  * @param string $user usuario de acceso a MySQL
  * @param string $pass contraseƱa del usuario de acceso a MySQL
  * @param string $db nombbre de esquema de MySQL
  * @throws DBException si no puede conectar o establecer el charset a utf8
  */
 public function __construct($host, $user, $pass, $db)
 {
     parent::init();
     /*
     if (!parent::options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
     	throw new exception('Setting MYSQLI_INIT_COMMAND failed');
     }
     
     if (!parent::options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
     	throw new exception('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
     }
     */
     if (!parent::real_connect($host, $user, $pass, $db)) {
         //throw new exception($this->connect_error, $this->connect_errno);
         //$connect_error falla hasta PHP 5.3.0, asi que usamos la siguiente
         throw new DBException(mysqli_connect_error(), mysqli_connect_errno());
     }
     /* change character set to utf8 */
     if (!parent::set_charset("utf8")) {
         throw new DBException(mysqli_connect_error(), mysqli_connect_errno());
     }
 }
 /**
  * Open a (persistent) connection to a MySQL server
  *
  * @return bool|void
  * @throws \RuntimeException
  */
 public function sql_pconnect()
 {
     if ($this->isConnected) {
         return $this->link;
     }
     if (!extension_loaded('mysqli')) {
         throw new \RuntimeException('Database Error: PHP mysqli extension not loaded. This is a must have for TYPO3 CMS!', 1271492607);
     }
     $host = $this->persistentDatabaseConnection ? 'p:' . $this->databaseHost : $this->databaseHost;
     $this->link = mysqli_init();
     $connected = $this->link->real_connect($host, $this->databaseUsername, $this->databaseUserPassword, null, (int) $this->databasePort, $this->databaseSocket, $this->connectionCompression ? MYSQLI_CLIENT_COMPRESS : 0);
     if ($connected) {
         $this->isConnected = true;
         if ($this->link->set_charset($this->connectionCharset) === false) {
             GeneralUtility::sysLog('Error setting connection charset to "' . $this->connectionCharset . '"', 'core', GeneralUtility::SYSLOG_SEVERITY_ERROR);
         }
         foreach ($this->initializeCommandsAfterConnect as $command) {
             if ($this->query($command) === false) {
                 GeneralUtility::sysLog('Could not initialize DB connection with query "' . $command . '": ' . $this->sql_error(), 'core', GeneralUtility::SYSLOG_SEVERITY_ERROR);
             }
         }
         $this->checkConnectionCharset();
     } else {
         // @todo This should raise an exception. Would be useful especially to work during installation.
         $error_msg = $this->link->connect_error;
         $this->link = null;
         GeneralUtility::sysLog('Could not connect to MySQL server ' . $host . ' with user ' . $this->databaseUsername . ': ' . $error_msg, 'core', GeneralUtility::SYSLOG_SEVERITY_FATAL);
     }
     return $this->link;
 }
Example #29
0
 public function real_connect($host = NULL, $user = NULL, $password = NULL, $database = NULL, $port = NULL, $socket = NULL, $flags = NULL)
 {
     $this->_db = $database;
     parent::real_connect($host, $user, $password, $database, $port, $socket, $flags);
 }
Example #30
-1
 /**
  * Connect
  *
  * @throws Exception\RuntimeException
  * @return $this
  */
 public function connect()
 {
     if ($this->resource instanceof \mysqli) {
         return $this;
     }
     // localize
     $p = $this->connectionParameters;
     // given a list of key names, test for existence in $p
     $findParameterValue = function (array $names) use($p) {
         foreach ($names as $name) {
             if (isset($p[$name])) {
                 return $p[$name];
             }
         }
         return;
     };
     $hostname = $findParameterValue(array('hostname', 'host'));
     $username = $findParameterValue(array('username', 'user'));
     $password = $findParameterValue(array('password', 'passwd', 'pw'));
     $database = $findParameterValue(array('database', 'dbname', 'db', 'schema'));
     $port = isset($p['port']) ? (int) $p['port'] : null;
     $socket = isset($p['socket']) ? $p['socket'] : null;
     $this->resource = new \mysqli();
     $this->resource->init();
     if (!empty($p['driver_options'])) {
         foreach ($p['driver_options'] as $option => $value) {
             if (is_string($option)) {
                 $option = strtoupper($option);
                 if (!defined($option)) {
                     continue;
                 }
                 $option = constant($option);
             }
             $this->resource->options($option, $value);
         }
     }
     $this->resource->real_connect($hostname, $username, $password, $database, $port, $socket);
     if ($this->resource->connect_error) {
         throw new Exception\RuntimeException('Connection error', null, new Exception\ErrorException($this->resource->connect_error, $this->resource->connect_errno));
     }
     if (!empty($p['charset'])) {
         $this->resource->set_charset($p['charset']);
     }
     return $this;
 }