/** * Connect to a database and log in as the specified user. * * @param string $dsn the data source name (see DB::parseDSN for syntax) * @param boolean $persistent (optional) whether the connection should * be persistent * @return mixed DB_OK on success, a DB error on failure * @access public */ function connect($dsninfo, $persistent = false) { if (!DB::assertExtension('mysqli')) { return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND); } $this->dsn = $dsninfo; $conn = false; @ini_set('track_errors', true); if ($this->getOption('ssl') === true) { $init = mysqli_init(); mysqli_ssl_set($init, empty($dsninfo['key']) ? null : $dsninfo['key'], empty($dsninfo['cert']) ? null : $dsninfo['cert'], empty($dsninfo['ca']) ? null : $dsninfo['ca'], empty($dsninfo['capath']) ? null : $dsninfo['capath'], empty($dsninfo['cipher']) ? null : $dsninfo['cipher']); if ($conn = @mysqli_real_connect($init, $dsninfo['hostspec'], $dsninfo['username'], $dsninfo['password'], $dsninfo['database'], $dsninfo['port'], $dsninfo['socket'])) { $conn = $init; } } else { $conn = @mysqli_connect($dsninfo['hostspec'], $dsninfo['username'], $dsninfo['password'], $dsninfo['database'], $dsninfo['port'], $dsninfo['socket']); } @ini_restore('track_errors'); if (!$conn) { if (($err = @mysqli_connect_error()) != '') { return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null, null, $err); } elseif (empty($php_errormsg)) { return $this->raiseError(DB_ERROR_CONNECT_FAILED); } else { return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null, null, $php_errormsg); } } if ($dsninfo['database']) { $this->_db = $dsninfo['database']; } $this->connection = $conn; return DB_OK; }
private function __construct() { $this->mysql = mysqli_init(); $conf = Vera_Conf::getConf('database'); $this->_connect($conf); $this->mysql->set_charset('utf8'); }
function sha_connect($offset, $host, $db, $port, $socket, $file) { $link = mysqli_init(); if (!$link->options(MYSQLI_SERVER_PUBLIC_KEY, $file)) { printf("[%03d + 001] mysqli_options failed, [%d] %s\n", $offset, $link->errno, $link->error); return false; } if (!$link->real_connect($host, 'shatest', 'shatest', $db, $port, $socket)) { printf("[%03d + 002] [%d] %s\n", $offset, $link->connect_errno, $link->connect_error); return false; } if (!($res = $link->query("SELECT id FROM test WHERE id = 1"))) { printf("[%03d + 003] [%d] %s\n", $offset, $link->errno, $link->error); } return false; if (!($row = mysqli_fetch_assoc($res))) { printf("[%03d + 004] [%d] %s\n", $offset, $link->errno, $link->error); return false; } if ($row['id'] != 1) { printf("[%03d + 005] Expecting 1 got %s/'%s'", $offset, gettype($row['id']), $row['id']); return false; } $res->close(); $link->close(); return true; }
/** * connects to the database server * * @uses $GLOBALS['cfg']['Server'] * @uses PMA_auth_fails() * @uses PMA_DBI_postConnect() * @uses MYSQLI_CLIENT_COMPRESS * @uses MYSQLI_OPT_LOCAL_INFILE * @uses strtolower() * @uses mysqli_init() * @uses mysqli_options() * @uses mysqli_real_connect() * @uses defined() * @param string $user mysql user name * @param string $password mysql user password * @param boolean $is_controluser * @return mixed false on error or a mysqli object on success */ function PMA_DBI_connect($user, $password, $is_controluser = false) { $server_port = empty($GLOBALS['cfg']['Server']['port']) ? false : (int) $GLOBALS['cfg']['Server']['port']; if (strtolower($GLOBALS['cfg']['Server']['connect_type']) == 'tcp') { $GLOBALS['cfg']['Server']['socket'] = ''; } // NULL enables connection to the default socket $server_socket = empty($GLOBALS['cfg']['Server']['socket']) ? null : $GLOBALS['cfg']['Server']['socket']; $link = mysqli_init(); mysqli_options($link, MYSQLI_OPT_LOCAL_INFILE, true); $client_flags = 0; /* Optionally compress connection */ if ($GLOBALS['cfg']['Server']['compress'] && defined('MYSQLI_CLIENT_COMPRESS')) { $client_flags |= MYSQLI_CLIENT_COMPRESS; } /* Optionally enable SSL */ if ($GLOBALS['cfg']['Server']['ssl'] && defined('MYSQLI_CLIENT_SSL')) { $client_flags |= MYSQLI_CLIENT_SSL; } $return_value = @mysqli_real_connect($link, $GLOBALS['cfg']['Server']['host'], $user, $password, false, $server_port, $server_socket, $client_flags); // Retry with empty password if we're allowed to if ($return_value == false && isset($cfg['Server']['nopassword']) && $cfg['Server']['nopassword'] && !$is_controluser) { $return_value = @mysqli_real_connect($link, $GLOBALS['cfg']['Server']['host'], $user, '', false, $server_port, $server_socket, $client_flags); } if ($return_value == false) { PMA_auth_fails(); } // end if PMA_DBI_postConnect($link, $is_controluser); return $link; }
function db_Connect($host = CMW_DB_HOST, $login = CMW_DB_LOGIN, $password = CMW_DB_PASSWORD, $name = CMW_DB_NAME, $port = _INI_MYSQLI_DEFAULT_PORT, $socket = _INI_MYSQLI_DEFAULT_SOCKET) { // Safely call this multiple times, only the first time has any effect // if (!db_IsConnected()) { global $db; $db = mysqli_init(); //mysqli_options($db, ...); if (defined('CMW_DB_PORT')) { $port = CMW_DB_PORT; } if (defined('CMW_DB_SOCKET')) { $socket = CMW_DB_SOCKET; } $flags = null; // Connect to the database // mysqli_real_connect($db, $host, $login, $password, $name, $port, $socket, $flags); // http://php.net/manual/en/mysqli.quickstart.connections.php if ($db->connect_errno) { db_Log("Failed to connect: (" . $db->connect_errno . ") " . $db->connect_error); } // Set character set to utf8mb4 mode (default is utf8mb3 (utf8). mb4 is required for Emoji) mysqli_set_charset($db, 'utf8mb4'); // More info: http://stackoverflow.com/questions/279170/utf-8-all-the-way-through } }
/** * Initialize database connection(s) * * Connects to the specified master database server, and also to the slave server if it is specified * * @param string Name of the database server - should be either 'localhost' or an IP address * @param integer Port of the database server - usually 3306 * @param string Username to connect to the database server * @param string Password associated with the username for the database server * @param string Persistent Connections - Not supported with MySQLi * @param string Configuration file from config.php.ini (my.ini / my.cnf) * @param string Mysqli Connection Charset PHP 5.1.0+ or 5.0.5+ / MySQL 4.1.13+ or MySQL 5.1.10+ Only * * @return object Mysqli Resource */ function db_connect($servername, $port, $username, $password, $usepconnect, $configfile = '', $charset = '') { set_error_handler(array($this, 'catch_db_error')); $link = mysqli_init(); # Set Options Connection Options if (!empty($configfile)) { mysqli_options($link, MYSQLI_READ_DEFAULT_FILE, $configfile); } try { // this will execute at most 5 times, see catch_db_error() do { $connect = $this->functions['connect']($link, $servername, $username, $password, '', $port); } while ($connect == false and $this->reporterror); } catch (Exception $e) { restore_error_handler(); throw $e; } restore_error_handler(); if (!empty($charset)) { if (function_exists('mysqli_set_charset')) { mysqli_set_charset($link, $charset); } else { $this->sql = "SET NAMES {$charset}"; $this->execute_query(true, $link); } } return !$connect ? false : $link; }
/** * @param object $link * @param array $options */ public function __construct($link = false, $options = array()) { foreach ($options as $key => $value) { $this->{$key} = $value; } if ($link) { $this->link = $link; } else { if (!empty($options)) { if (isset($this->host)) { $this->hostname = $this->host; } if (isset($this->dbname)) { $this->database = $this->dbname; } //$this->link = @mysqli_connect($this->hostname, $this->username, $this->password, $this->database); $this->link = mysqli_init(); mysqli_options($this->link, MYSQLI_OPT_CONNECT_TIMEOUT, 1); if (@mysqli_real_connect($this->link, $this->hostname, $this->username, $this->password, $this->database)) { $names = "SET NAMES '" . $this->charset . "';"; mysqli_query($this->link, $names); $charset = "SET CHARSET '" . $this->charset . "';"; mysqli_query($this->link, $charset); } else { $this->link = false; } } } }
/** * Установка соединения * * @return bool * * @throws \Cms\Db\Engine\Driver\Exception\ConnectionException */ public function connect() { $resource = null; $this->resource = null; $this->connected = false; $host = $this->host; if ($this->isPersistent()) { $host = 'p:' . $host; } try { $resource = mysqli_init(); $resource->set_opt(MYSQLI_OPT_CONNECT_TIMEOUT, $this->timeout); $resource->real_connect($host, $this->user, $this->password, $this->database, intval($this->port)); } catch (\Exception $e) { $msg = sprintf('Не удалось установить соединение с базой данных "%s": %s', $this->database, $e->getMessage()); throw new ConnectionException($msg, $e->getCode()); } if ($resource->connect_errno) { $msg = sprintf('Не удалось установить соединение с базой данных "%s": %s', $this->database, $resource->connect_error); throw new ConnectionException($msg, $resource->connect_errno); } $this->resource = $resource; $this->connected = true; $this->executeConnectQueries(); return true; }
public function __construct($dsn) { $base = preg_replace('{^/}s', '', $dsn['path']); if (!class_exists('mysqli')) { return $this->_setLastError('-1', 'mysqli extension is not loaded', 'mysqli'); } try { $this->link = mysqli_init(); if (!$this->link) { $this->_setLastError(-1, 'mysqli_init failed', 'new mysqli'); } else { if (!$this->link->options(MYSQLI_OPT_CONNECT_TIMEOUT, isset($dsn['timeout']) && $dsn['timeout'] ? $dsn['timeout'] : 0)) { $this->_setLastError($this->link->connect_errno, $this->link->connect_error, 'new mysqli'); } else { if (!$this->link->real_connect(isset($dsn['persist']) && $dsn['persist'] ? 'p:' . $dsn['host'] : $dsn['host'], $dsn['user'], isset($dsn['pass']) ? $dsn['pass'] : '', $base, empty($dsn['port']) ? NULL : $dsn['port'], NULL, isset($dsn['compression']) && $dsn['compression'] ? MYSQLI_CLIENT_COMPRESS : NULL)) { $this->_setLastError($this->link->connect_errno, $this->link->connect_error, 'new mysqli'); } else { if (!$this->link->set_charset(isset($dsn['enc']) ? $dsn['enc'] : 'UTF8')) { $this->_setLastError($this->link->connect_errno, $this->link->connect_error, 'new mysqli'); } else { $this->isMySQLnd = method_exists('mysqli_result', 'fetch_all'); } } } } $this->isMySQLnd = method_exists('mysqli_result', 'fetch_all'); } catch (mysqli_sql_exception $e) { $this->_setLastError($e->getCode(), $e->getMessage(), 'new mysqli'); } }
protected function _connect() { //try { $this->_config = App::$_registry["db"]; //pr($this->_config);exit; // if connected return if ($this->_connection) { return; } if (isset($this->_config['port'])) { $port = (int) $this->_config['port']; } else { $port = null; } $this->_connection = mysqli_init(); $_isConnected = @mysqli_real_connect($this->_connection, $this->_config['host'], $this->_config['username'], $this->_config['password'], $this->_config['dbname'], $port, null, MYSQLI_CLIENT_FOUND_ROWS); if ($_isConnected === false || mysqli_connect_errno()) { $this->closeConnection(); //throw new \Exception(mysqli_connect_error()); show_error('DB Error', mysqli_connect_error()); } //} /* catch (\Exception $e) { echo $e->getTraceAsString(); } */ }
/** * 连接数据库 * * @param array $config * @return string 返回连接的id */ public function doConnect(array &$config) { try { if (empty($persistent)) { $resource = \mysqli_init(); \mysqli_options($resource, \MYSQLI_OPT_CONNECT_TIMEOUT, 3); if (isset($this->config['option']) && is_array($this->config['option'])) { foreach ($this->config['option'] as $k => $v) { \mysqli_options($resource, $k, $v); } } \mysqli_real_connect($resource, $config['hostname'], $config['username'], $config['password'], $config['database'], $config['port'], null, \MYSQLI_CLIENT_COMPRESS); } else { $resource = new \mysqli($config['hostname'], $config['username'], $config['password'], $config['database'], $config['port']); } # 设置语言 $resource->set_charset($this->config['charset']); return $resource; } catch (Exception $e) { if (2 === $e->getCode() && preg_match('#(Unknown database|Access denied for user)#i', $e->getMessage(), $m)) { # 指定的库不存在,直接返回 $lastError = strtolower($m[1]) === 'unknown database' ? __('The mysql database does not exist') : __('The mysql database account or password error'); } else { $lastError = $e->getMessage(); } $lastErrorCode = $e->getCode(); } throw new Exception($lastError, $lastErrorCode); }
/** * Connect to the database * * @return bool false on failure / mysqli MySQLi object instance on success */ public function connect() { // Try and connect to the database // if (!isset(self::$connection)) { // Load configuration as an array. Use the actual location of your configuration file // self::$connection = new mysqli('localhost', 'root', 'root', 'servicioslegales'); // } self::$connection = mysqli_init(); if (!self::$connection) { die('mysqli_init failed'); } if (!self::$connection->options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) { die('Setting MYSQLI_INIT_COMMAND failed'); } if (!self::$connection->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) { die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed'); } if (!self::$connection->real_connect('localhost', 'root', 'root', 'servicioslegales')) { die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error()); } // If connection was not successful, handle the error if (self::$connection === false) { // Handle error - notify administrator, log to a file, show an error screen, etc. return false; } return self::$connection; }
protected function __construct() { $this->mysqli = mysqli_init(); if (!$this->mysqli->real_connect(Configuration::read('db_host'), Configuration::read('db_username'), Configuration::read('db_password'), Configuration::read('db_name'))) { throw new MysqliConnectionException('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error()); } }
/** * Database connection * * @param array $conf * @return bool|resource */ private function connect() { if ($this->driver == 'ext/mysqli') { $link = mysqli_init(); if (!$link) { $link = false; } else { $link = @mysqli_connect($this->host, $this->user, $this->password); if ($link !== false) { $db = @mysqli_select_db($link, $this->db); mysqli_set_charset($link, "utf8"); } } if ($link === false) { $this->error('MySQL connection error: ' . mysqli_connect_error()); } } else { $link = @mysql_connect($this->host, $this->user, $this->password); if ($link !== false) { $db = @mysql_select_db($this->db, $link); mysql_query("SET NAMES 'utf8'"); } else { if ($link === false) { $this->error('MySQL connection error: ' . mysql_error()); } } } return $link; }
/** * Opens the database connection. * * @return bool Boolean true on success, throws a RuntimeException otherwise */ public function open() { if (is_object($this->link)) { return true; } if ($this->ssl == true) { if (empty($this->clientcert)) { throw new \RuntimeException("clientcert not defined"); } if (empty($this->clientkey)) { throw new \RuntimeException("clientkey not defined"); } if (empty($this->cacert)) { throw new \RuntimeException("cacert not defined"); } $this->link = mysqli_init(); $this->link->options(MYSQLI_OPT_SSL_VERIFY_SERVER_CERT, true); $this->link->ssl_set($this->clientkey, $this->clientcert, $this->cacert, NULL, NULL); $this->link->real_connect($this->host, $this->username, $this->password, $this->database, $this->port, $this->socket, MYSQLI_CLIENT_SSL); } else { $this->link = mysqli_connect($this->host, $this->username, $this->password, $this->database, $this->port, $this->socket); } if (mysqli_connect_errno()) { throw new \RuntimeException(sprintf('could not connect to %s : (%d) %s', $this->database, mysqli_connect_errno(), mysqli_connect_error())); } if (!mysqli_set_charset($this->link, $this->charset)) { throw new \RuntimeException(sprintf('error loading character set %s : (%d) %s', $this->charset, mysqli_errno($this->link), mysqli_error($this->link))); } return true; }
public final function __construct($Server, $Username, $Password, $Name, $Timeout = 30) { $this->DB_server = $Server; $this->DB_user = $Username; $this->DB_passwd = $Password; $this->DB_name = $Name; $this->DB_timeout = $Timeout; $this->mySQLi = mysqli_init(); if (!$this->mySQLi) { die($this->mySQLi->error); } else { if ($this->DB_timeout != 0) { $this->mySQLi->options(MYSQLI_OPT_CONNECT_TIMEOUT, $this->DB_timeout); } } if ($this->connect()) { $this->connected = true; } else { $this->connected = false; if (DEBUG_MODE) { die($this->mySQLi->error); } } if ($this->selectDB()) { $this->connected = true; return true; } else { $this->connected = false; if (DEBUG_MODE) { die($this->mySQLi->error); } return false; } }
public function connect() { if ($this->_connection) { return; } if (static::$_set_names === null) { // Determine if we can use mysqli_set_charset(), which is only // available on PHP 5.2.3+ when compiled against MySQL 5.0+ static::$_set_names = !function_exists('mysqli_set_charset'); } // Extract the connection parameters, adding required variables extract($this->_config['connection'] + array('database' => '', 'hostname' => '', 'port' => '', 'socket' => '', 'username' => '', 'password' => '', 'persistent' => false, 'compress' => true)); // Prevent this information from showing up in traces unset($this->_config['connection']['username'], $this->_config['connection']['password']); try { if ($socket != '') { $port = null; } elseif ($port != '') { $socket = null; } else { $socket = null; $port = null; } if ($persistent) { // Create a persistent connection if ($compress) { $mysqli = mysqli_init(); $mysqli->real_connect('p:' . $hostname, $username, $password, $database, $port, $socket, MYSQLI_CLIENT_COMPRESS); $this->_connection = $mysqli; } else { $this->_connection = new \MySQLi('p:' . $hostname, $username, $password, $database, $port, $socket); } } else { // Create a connection and force it to be a new link if ($compress) { $mysqli = mysqli_init(); $mysqli->real_connect($hostname, $username, $password, $database, $port, $socket, MYSQLI_CLIENT_COMPRESS); $this->_connection = $mysqli; } else { $this->_connection = new \MySQLi($hostname, $username, $password, $database, $port, $socket); } } if ($this->_connection->error) { // Unable to connect, select database, etc throw new \Database_Exception($this->_connection->error, $this->_connection->errno); } } catch (\ErrorException $e) { // No connection exists $this->_connection = null; throw new \Database_Exception('No MySQLi Connection<br>\\n' . $e->getMessage() . "<br>\n" . "hostname:" . $hostname . "<br>\n" . "username:"******"<br>\n" . "password:"******"<br>\n" . "database:" . $database . "<br>\n" . "port:" . $port . "<br>\n", 0); throw new \Database_Exception('No MySQLi Connection', 0); } // \xFF is a better delimiter, but the PHP driver uses underscore $this->_connection_id = sha1($hostname . '_' . $username . '_' . $password); if (!empty($this->_config['charset'])) { // Set the character set $this->set_charset($this->_config['charset']); } static::$_current_databases[$this->_connection_id] = $database; }
public function __construct($dbName, $dbHost, $dbUser, $dbPassword, $Port, $Socket, $dbFlags, $NoUTF8) { $this->dbObject = mysqli_init(); if ($this->dbObject === FALSE) { $this->TriggerSQLError("Could not initialize MySQLi object for [{$dbName}]"); } $this->dbObject->options(MYSQLI_OPT_LOCAL_INFILE, true); if (is_null($dbFlags)) { $connect = $this->dbObject->real_connect($dbHost, $dbUser, $dbPassword, $dbName, $Port, $Socket, MYSQLI_CLIENT_FOUND_ROWS); } else { $connect = $this->dbObject->real_connect($dbHost, $dbUser, $dbPassword, $dbName, $Port, $Socket, $dbFlags); } if ($connect === FALSE) { $this->TriggerSQLError("Error connecting to database {$dbName}, error number [{$this->dbObject->connect_errno}] message {$this->dbObject->connect_error}"); } $this->dbObject->real_query("set net_write_timeout=1200"); $Version = phpversion(); $VerInfo = explode(".", $Version); if ($NoUTF8 === FALSE && ($VerInfo[0] > 5 || $VerInfo[0] == 5 && $VerInfo[1] >= 3)) { $this->dbObject->set_charset("utf8"); } $this->DatabaseName = $dbName; $this->UserName = $dbUser; $this->Pwd = $dbPassword; $this->HostName = $dbHost; }
public function connect() { require_once "connect.inc"; $link = my_mysqli_connect($host, $user, $passwd, $db, $port, $socket); var_dump($link); $link = mysqli_init(); /* @ is to suppress 'Property access is not allowed yet' */ @var_dump($link); $mysql = new my_mysqli($host, $user, $passwd, $db, $port, $socket); $mysql->query("DROP TABLE IF EXISTS test_bug34810_table_1"); $mysql->query("CREATE TABLE test_bug34810_table_1 (a int not null)"); $mysql->query("SET sql_mode=''"); $mysql->query("INSERT INTO test_bug34810_table_1 VALUES (1),(2),(NULL)"); $warning = $mysql->get_warnings(); if (!$warning) { printf("[001] No warning!\n"); } if ($warning->errno == 1048 || $warning->errno == 1253) { /* 1048 - Column 'a' cannot be null, 1263 - Data truncated; NULL supplied to NOT NULL column 'a' at row */ if ("HY000" != $warning->sqlstate) { printf("[003] Wrong sql state code: %s\n", $warning->sqlstate); } if ("" == $warning->message) { printf("[004] Message string must not be empty\n"); } } else { printf("[002] Empty error message!\n"); var_dump($warning); } }
/** Connect to a mysql database using mysqli. * * @param array $db_config Connection information. */ public function connect($db_host = null, $db_user = null, $db_pass = null, $db = null) { $this->db_config = array('db_host' => $db_host, 'db_user' => $db_user, 'db_pass' => $db_pass, 'db' => $db); $this->mysqli = mysqli_init(); $this->mysqli->real_connect($db_host, $db_user, $db_pass, $db); $this->mysqli->set_charset("utf8"); }
/** * Выполнение запроса к базе данных, выполняет коннект на запросе * * @param string $query * @param array $params * @param int $shard_id * @throws Exception */ public static function query($query, array $params = [], $shard_id = 0) { assert("is_string(\$query)"); assert("\\is_array(\$params)"); assert("is_int(\$shard_id)"); assert("\$shard_id >= 0 && \$shard_id < 4096 /* only 4096 shards allowed */"); static $time = 0; if (!static::$shards) { static::$shards = config('mysql.shard'); } if (!static::$pool) { mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); } if (!isset(static::$shards[$shard_id])) { trigger_error('No shards for mysql server specified'); } // Если на этом шарде еще коннетка нет if (!isset(static::$pool[$shard_id])) { $dsn =& static::$shards[$shard_id]; $dsn_key = function ($key) use($dsn) { preg_match("|{$key}=([^;]+)|", $dsn, $m); return $m ? $m[1] : null; }; $DB =& static::$pool[$shard_id]; $DB = mysqli_init(); $DB->options(MYSQLI_OPT_CONNECT_TIMEOUT, config('mysql.connect_timeout')); $DB->real_connect($dsn_key('host'), $dsn_key('user'), $dsn_key('password'), $dsn_key('dbname'), $dsn_key('port')); } $DB =& static::$pool[$shard_id]; if (range(0, sizeof($params) - 1) === array_keys($params)) { $query = preg_replace_callback('|\\?|', function () { static $count = 0; return ':' . $count++; }, $query); } $params = array_combine(array_map(function ($k) { return ':' . $k; }, array_keys($params)), array_map(function ($item) use($DB) { return filter_var($item, FILTER_VALIDATE_INT | FILTER_VALIDATE_FLOAT | FILTER_VALIDATE_BOOLEAN) ? $item : '"' . $DB->real_escape_string($item) . '"'; }, $params)); $Result = $DB->query(strtr($query, $params)); // Определяем результат работы функции в зависимости от типа запроса к базе switch (strtolower(strtok($query, ' '))) { case 'insert': return $DB->insert_id ?: $DB->affected_rows; break; case 'update': case 'delete': return $DB->affected_rows; break; case 'select': case 'describe': $result = $Result->fetch_all(MYSQLI_ASSOC); $Result->close(); return $result; break; default: trigger_error('Undefined call for database query'); } }
/** * 连接数据库 * @param array $array 数据库连接配置 * $array=array( * 'dbmysql_server', * 'dbmysql_username', * 'dbmysql_password', * 'dbmysql_name', * 'dbmysql_pre', * 'dbmysql_port', * 'persistent' * 'engine') * @return bool */ public function Open($array) { $db = mysqli_init(); if ($array[6] == true) { $array[0] = 'p:' . $array[0]; } //mysqli_options($db,MYSQLI_READ_DEFAULT_GROUP,"max_allowed_packet=50M"); if (@mysqli_real_connect($db, $array[0], $array[1], $array[2], $array[3], $array[5])) { $myver = mysqli_get_server_info($db); $this->version = substr($myver, 0, strpos($myver, "-")); if (version_compare($this->version, '5.5.3') >= 0) { $u = "utf8mb4"; } else { $u = "utf8"; } if (mysqli_set_charset($db, $u) == false) { mysqli_set_charset($db, "utf8"); } $this->db = $db; $this->dbname = $array[3]; $this->dbpre = $array[4]; $this->dbengine = $array[7]; return true; } return false; }
public function __construct($host = null, $username = null, $password = null, $dbname = '', $port = null, $socket = null) { assert('is_string($host) || is_null($host)'); assert('is_string($username) || is_null($username)'); assert('is_string($password) || is_null($password)'); assert('is_string($dbname)'); assert('is_int($port) || is_null($port)'); assert('is_string($socket) || is_null($socket)'); if (is_null($host)) { $host = ini_get("mysqli.default_host"); } $this->_host = $host; if (is_null($username)) { $username = ini_get("mysqli.default_user"); } $this->_username = $username; if (is_null($password)) { $password = ini_get("mysqli.default_pw"); } $this->_password = $password; $this->_dbname = $dbname; if (is_null($port)) { $port = ini_get("mysqli.default_port"); } $this->_port = $port; if (is_null($socket)) { $socket = ini_get("mysqli.default_socket"); } $this->_socket = $socket; $this->_mysql = mysqli_init(); }
/** * 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; }
function _connect($argHostname = NULL, $argUsername = NULL, $argPassword = NULL, $argDatabasename = NULL, $persist = false) { if (!extension_loaded("mysqli")) { return null; } $this->_connectionID = @mysqli_init(); if (is_null($this->_connectionID)) { // mysqli_init only fails if insufficient memory if ($this->debug) { ADOConnection::outp("mysqli_init() failed : " . $this->ErrorMsg()); } return false; } /* I suggest a simple fix which would enable adodb and mysqli driver to read connection options from the standard mysql configuration file /etc/my.cnf - "Bastien Duclaux" <bduclaux#yahoo.com> */ foreach ($this->optionFlags as $arr) { mysqli_options($this->_connectionID, $arr[0], $arr[1]); } #if (!empty($this->port)) $argHostname .= ":".$this->port; $ok = mysqli_real_connect($this->_connectionID, $argHostname, $argUsername, $argPassword, $argDatabasename, $this->port, $this->socket, $this->clientFlags); if ($ok) { if ($argDatabasename) { return $this->SelectDB($argDatabasename); } return true; } else { if ($this->debug) { ADOConnection::outp("Could't connect : " . $this->ErrorMsg()); } return false; } }
public function __construct($enableProfiling = false) { $this->mysql = mysqli_init(); if ($enableProfiling) { $this->enableProfiling(true); } }
function _connect($argHostname = NULL, $argUsername = NULL, $argPassword = NULL, $argDatabasename = NULL, $persist = false) { if (!extension_loaded("mysqli")) { return null; } $this->_connectionID = @mysqli_init(); if (is_null($this->_connectionID)) { // mysqli_init only fails if insufficient memory if ($this->debug) { ADOConnection::outp("mysqli_init() failed : " . $this->ErrorMsg()); } return false; } // Set connection options // Not implemented now // mysqli_options($this->_connection,,); if (mysqli_real_connect($this->_connectionID, $argHostname, $argUsername, $argPassword, $argDatabasename, $this->port, $this->socket, $this->clientFlags)) { if ($argDatabasename) { return $this->SelectDB($argDatabasename); } return true; } else { if ($this->debug) { ADOConnection::outp("Could't connect : " . $this->ErrorMsg()); } return false; } }
/** * connect * Crea conexión SQL */ public function connect($dbhost, $dbuser, $dbpass, $dbname, $port, $socket, $return_error = false) { //TODO: NO DA FALLO CON CONEXIÓN MALA $result = true; ini_set("display_errors", 0); $this->con = mysqli_init(); if (!$this->con) { die('mysqli_init failed'); } if (!$this->con->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) { die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed'); } if (!$this->con->real_connect($dbhost, $dbuser, $dbpass, $dbname, $port)) { if ($return_error === true) { $result = mysqli_connect_errno(); } } ini_set("display_errors", 1); /* check connection */ if (($this->con->connect_error || $this->con->error) && $return_error === false) { $texto_error = "[ERROR " . get_class($this) . "::" . __FUNCTION__ . "::" . __LINE__ . "] Se produjo un error: " . $this->con->connect_error . "\n" . $this->con->error; $this->sendError($texto_error); } if ($result === true) { $this->con->set_charset("utf8"); } return $result; }
/** * @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 static function tryToConnect($server, $user, $pwd, $db, $newDbLink = true, $engine = null, $timeout = 5) { $link = mysqli_init(); if (!$link) { return -1; } if (!$link->options(MYSQLI_OPT_CONNECT_TIMEOUT, $timeout)) { return 1; } if (!$link->real_connect($server, $user, $pwd, $db)) { return mysqli_connect_errno() == 1049 ? 2 : 1; } if (strtolower($engine) == 'innodb') { $sql = 'SHOW VARIABLES WHERE Variable_name = \'have_innodb\''; $result = $link->query($sql); if (!$result) { return 4; } $row = $result->fetch_assoc(); if (!$row || strtolower($row['Value']) != 'yes') { return 4; } } $link->close(); return 0; }