Пример #1
0
/**
 * 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;
}
Пример #2
0
 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;
     }
 }
Пример #3
0
 /**
  * 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;
 }
Пример #4
0
 /**
  * 连接数据库
  *
  * @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);
 }
Пример #5
0
 /**
  * @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;
             }
         }
     }
 }
Пример #6
0
 /**
  */
 function connect()
 {
     $this->db_connect_id = mysqli_init();
     if (!$this->db_connect_id) {
         $this->_connect_error = 'cannot_connect_to_server';
         $this->db_connect_id = null;
         return false;
     }
     foreach ((array) $this->INI_OPTS as $ini_name => $ini_val) {
         ini_set($ini_name, $ini_val);
     }
     if (!$this->ON_BEFORE_CONNECT) {
         $this->ON_BEFORE_CONNECT[] = function () {
             return $this->_on_before_connect_default();
         };
     }
     foreach ((array) $this->ON_BEFORE_CONNECT as $func) {
         if (is_callable($func)) {
             $func($this);
         }
     }
     if ($this->params['socket']) {
         $connect_host = $this->params['socket'];
     } else {
         $connect_port = $this->params['port'] && $this->params['port'] != $this->DEF_PORT ? $this->params['port'] : '';
         $connect_host = ($this->params['persist'] ? 'p:' : '') . $this->params['host'] . ($connect_port ? ':' . $connect_port : '');
     }
     mysqli_options($this->db_connect_id, MYSQLI_OPT_CONNECT_TIMEOUT, $this->CONNECT_TIMEOUT);
     $is_connected = mysqli_real_connect($this->db_connect_id, $this->params['host'], $this->params['user'], $this->params['pswd'], '', $this->params['port'], $this->params['socket'], $this->params['ssl'] ? MYSQLI_CLIENT_SSL : 0);
     if (!$is_connected) {
         $this->_connect_error = 'cannot_connect_to_server';
         return false;
     } else {
         foreach ((array) $this->SQL_AFTER_CONNECT as $sql) {
             $this->query($sql);
         }
     }
     if ($this->params['name'] != '') {
         $dbselect = $this->select_db($this->params['name']);
         // Try to create database, if not exists and if allowed
         if (!$dbselect && $this->params['allow_auto_create_db'] && preg_match('/^[a-z0-9][a-z0-9_]+[a-z0-9]$/i', $this->params['name'])) {
             $res = $this->query('CREATE DATABASE IF NOT EXISTS ' . $this->params['name']);
             if ($res) {
                 $dbselect = $this->select_db($this->params['name']);
             }
         }
         if (!$dbselect) {
             $this->_connect_error = 'cannot_select_db';
         }
         foreach ((array) $this->ON_AFTER_CONNECT as $func) {
             if (is_callable($func)) {
                 $func($this, $dbselect);
             }
         }
         return $dbselect;
     }
 }
Пример #7
0
 public static function getConnection($index = DB_SLAVE)
 {
     $index = !empty($index) ? $index : DB_SLAVE;
     if (empty(self::$instance[$index]) || empty(self::$instance[$index]->connection->client_info) || !is_object(self::$instance[$index])) {
         self::$instance[$index] = new Database($index);
         mysqli_options(self::$instance[$index], MYSQLI_OPT_CONNECT_TIMEOUT, 10);
     }
     return self::$instance[$index];
 }
Пример #8
0
/**
 * 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
 * @param   array   $server host/port/socket
 * @param   boolean $auxiliary_connection (when true, don't go back to login if connection fails)
 * @return  mixed   false on error or a mysqli object on success
 */
function PMA_DBI_connect($user, $password, $is_controluser = false, $server = null, $auxiliary_connection = false)
{
    if ($server) {
        $server_port = empty($server['port']) ? false : (int) $server['port'];
        $server_socket = empty($server['socket']) ? '' : $server['socket'];
        $server['host'] = empty($server['host']) ? 'localhost' : $server['host'];
    } else {
        $server_port = empty($GLOBALS['cfg']['Server']['port']) ? false : (int) $GLOBALS['cfg']['Server']['port'];
        $server_socket = empty($GLOBALS['cfg']['Server']['socket']) ? null : $GLOBALS['cfg']['Server']['socket'];
    }
    if (strtolower($GLOBALS['cfg']['Server']['connect_type']) == 'tcp') {
        $GLOBALS['cfg']['Server']['socket'] = '';
    }
    // NULL enables connection to the default 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;
    }
    if (!$server) {
        $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($GLOBALS['cfg']['Server']['nopassword']) && $GLOBALS['cfg']['Server']['nopassword'] && !$is_controluser) {
            $return_value = @mysqli_real_connect($link, $GLOBALS['cfg']['Server']['host'], $user, '', false, $server_port, $server_socket, $client_flags);
        }
    } else {
        $return_value = @mysqli_real_connect($link, $server['host'], $user, $password, false, $server_port, $server_socket);
    }
    if ($return_value == false) {
        if ($is_controluser) {
            trigger_error(__('Connection for controluser as defined in your configuration failed.'), E_USER_WARNING);
            return false;
        }
        // we could be calling PMA_DBI_connect() to connect to another
        // server, for example in the Synchronize feature, so do not
        // go back to main login if it fails
        if (!$auxiliary_connection) {
            PMA_log_user($user, 'mysql-denied');
            PMA_auth_fails();
        } else {
            return false;
        }
    } else {
        PMA_DBI_postConnect($link, $is_controluser);
    }
    return $link;
}
Пример #9
0
 protected final function __construct($config)
 {
     $this->_db_engine = 'MySQLi';
     $this->_db_connect_id = new mysqli($config['dbhost'], $config['dbusername'], $config['dbpassword'], $config['dbdatabase']);
     mysqli_options($this->_db_connect_id, MYSQLI_OPT_LOCAL_INFILE, true);
     if ($this->_db_connect_id->connect_error) {
         trigger_error($this->_db_connect_id->connect_error, E_USER_ERROR);
     }
     $this->_prefix = $config['dbprefix'];
     $this->_setup();
     //Run the parent constructor
     parent::__construct();
 }
Пример #10
0
 /**
  * Connects to a database.
  * @return void
  * @throws Dibi\Exception
  */
 public function connect(array &$config)
 {
     mysqli_report(MYSQLI_REPORT_OFF);
     if (isset($config['resource'])) {
         $this->connection = $config['resource'];
     } else {
         // default values
         $config += ['charset' => 'utf8', 'timezone' => date('P'), 'username' => ini_get('mysqli.default_user'), 'password' => ini_get('mysqli.default_pw'), 'socket' => (string) ini_get('mysqli.default_socket'), 'port' => NULL];
         if (!isset($config['host'])) {
             $host = ini_get('mysqli.default_host');
             if ($host) {
                 $config['host'] = $host;
                 $config['port'] = ini_get('mysqli.default_port');
             } else {
                 $config['host'] = NULL;
                 $config['port'] = NULL;
             }
         }
         $foo =& $config['flags'];
         $foo =& $config['database'];
         $this->connection = mysqli_init();
         if (isset($config['options'])) {
             if (is_scalar($config['options'])) {
                 $config['flags'] = $config['options'];
                 // back compatibility
                 trigger_error(__CLASS__ . ": configuration item 'options' must be array; for constants MYSQLI_CLIENT_* use 'flags'.", E_USER_NOTICE);
             } else {
                 foreach ((array) $config['options'] as $key => $value) {
                     mysqli_options($this->connection, $key, $value);
                 }
             }
         }
         @mysqli_real_connect($this->connection, (empty($config['persistent']) ? '' : 'p:') . $config['host'], $config['username'], $config['password'], $config['database'], $config['port'], $config['socket'], $config['flags']);
         // intentionally @
         if ($errno = mysqli_connect_errno()) {
             throw new Dibi\DriverException(mysqli_connect_error(), $errno);
         }
     }
     if (isset($config['charset'])) {
         if (!@mysqli_set_charset($this->connection, $config['charset'])) {
             $this->query("SET NAMES '{$config['charset']}'");
         }
     }
     if (isset($config['sqlmode'])) {
         $this->query("SET sql_mode='{$config['sqlmode']}'");
     }
     if (isset($config['timezone'])) {
         $this->query("SET time_zone='{$config['timezone']}'");
     }
     $this->buffered = empty($config['unbuffered']);
 }
Пример #11
0
 public function Connect()
 {
     /*$this->link = new MySQLi($this->host, $this->user, $this->pass);
       $this->link->select_db($this->dbName);
       $this->link->set_charset("utf8");*/
     $this->link = mysqli_init();
     mysqli_options($this->link, MYSQLI_OPT_LOCAL_INFILE, true);
     mysqli_real_connect($this->link, $this->host, $this->user, $this->pass, $this->dbName);
     $this->link->select_db($this->dbName);
     $this->link->set_charset("utf8");
     if (mysqli_connect_errno()) {
         return mysqli_connect_error();
     } else {
         return $this->link;
     }
 }
Пример #12
0
 protected final function __construct($config)
 {
     $this->_db_engine = 'MySQLi';
     $dbport = isset($config['dbport']) && !empty($config['dbport']) ? $config['dbport'] : ini_get('mysqli.default_port');
     $dbsocket = isset($config['dbsocket']) && !empty($config['dbsocket']) ? $config['dbsocket'] : ini_get('mysqli.default_socket');
     $this->_db_connect_id = new mysqli($config['dbhost'], $config['dbusername'], $config['dbpassword'], $config['dbdatabase'], $dbport, $dbsocket);
     mysqli_options($this->_db_connect_id, MYSQLI_OPT_LOCAL_INFILE, true);
     if ($this->_db_connect_id->connect_error) {
         trigger_error($this->_db_connect_id->connect_error, E_USER_ERROR);
     } else {
         $this->connected = true;
     }
     $this->_prefix = $config['dbprefix'];
     $this->_setup();
     //Run the parent constructor
     parent::__construct();
 }
Пример #13
0
 /**
  * Creates connection to database
  *
  * @return void
  */
 protected function _connect()
 {
     $this->_link = mysqli_init();
     if (!$this->_link) {
         die('mysqli_init failed.');
     }
     if (!mysqli_options($this->_link, MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
         die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed.');
     }
     mysqli_real_connect($this->_link, INTELLI_DBHOST, INTELLI_DBUSER, INTELLI_DBPASS, INTELLI_DBNAME, INTELLI_DBPORT);
     if (!$this->_link) {
         $message = !INTELLI_DEBUG ? 'Could not connect.' : 'Could not connect to the database. For more information see error logs.';
         die($message);
     }
     // set active database again
     mysqli_select_db($this->_link, INTELLI_DBNAME);
     $this->query("SET NAMES 'utf8'");
 }
Пример #14
0
 protected function _connect()
 {
     if ($this->_connection) {
         return;
     }
     if (!extension_loaded('mysqli')) {
         throw new \Exception('The Mysqli extension is required for this adapter but the extension is not loaded');
     }
     if (isset($this->_config['port'])) {
         $port = (int) $this->_config['port'];
     } else {
         $port = null;
     }
     $this->_connection = mysqli_init();
     if (!empty($this->_config['driver_options'])) {
         foreach ($this->_config['driver_options'] as $option => $value) {
             if (is_string($option)) {
                 // Suppress warnings here
                 // Ignore it if it's not a valid constant
                 $option = @constant(strtoupper($option));
                 if ($option === null) {
                     continue;
                 }
             }
             @mysqli_options($this->_connection, $option, $value);
         }
     }
     // Suppress connection warnings here.
     // Throw an exception instead.
     try {
         $_isConnected = mysqli_real_connect($this->_connection, $this->_config['hostname'], $this->_config['username'], $this->_config['password'], $this->_config['database'], $port);
     } catch (Exception $e) {
         $_isConnected = false;
     }
     if ($_isConnected === false || mysqli_connect_errno()) {
         $this->closeConnection();
         throw new \Exception(mysqli_connect_error());
     }
     if ($_isConnected && !empty($this->_config['charset'])) {
         mysqli_set_charset($this->_connection, $this->_config['charset']);
     }
 }
Пример #15
0
function PMA_DBI_connect($user, $password, $is_controluser = FALSE)
{
    global $cfg, $php_errormsg;
    $server_port = empty($cfg['Server']['port']) ? FALSE : (int) $cfg['Server']['port'];
    if (strtolower($cfg['Server']['connect_type']) == 'tcp') {
        $cfg['Server']['socket'] = '';
    }
    // NULL enables connection to the default socket
    $server_socket = empty($cfg['Server']['socket']) ? null : $cfg['Server']['socket'];
    $link = mysqli_init();
    mysqli_options($link, MYSQLI_OPT_LOCAL_INFILE, TRUE);
    $client_flags = $cfg['Server']['compress'] && defined('MYSQLI_CLIENT_COMPRESS') ? MYSQLI_CLIENT_COMPRESS : 0;
    $return_value = @mysqli_real_connect($link, $cfg['Server']['host'], $user, $password, FALSE, $server_port, $server_socket, $client_flags);
    if ($return_value == FALSE) {
        PMA_auth_fails();
    }
    // end if
    PMA_DBI_postConnect($link, $is_controluser);
    return $link;
}
Пример #16
0
function GetMySQLLink($host, $uname, $passwd, $port, $db = NULL)
{
    if (!(function_exists('mysqli_init') && ($link = mysqli_init()))) {
        return "Can't initialize MySQL connection. Please make sure your PHP has the mysqli extension.";
    }
    if (!mysqli_options($link, MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 1')) {
        return 'Setting MYSQLI_INIT_COMMAND failed';
    }
    if (!mysqli_options($link, MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
        return 'Setting MYSQLI_OPT_CONNECT_TIMEOUT failed';
    }
    if (function_exists('mysqli_fetch_all')) {
        $host = 'p:' . $host;
    }
    if (!mysqli_real_connect($link, $host, $uname, $passwd, $db, $port)) {
        return 'MySQL connect error #' . mysqli_connect_errno() . ': ' . mysqli_connect_error();
    }
    $link->set_charset("utf8");
    return $link;
}
 function db_connect()
 {
     $this->link = mysqli_init();
     foreach ($this->options as $key => $val) {
         mysqli_options($this->link, $key, $val);
     }
     $this->link = @mysqli_connect($this->host, $this->username, $this->password, '', $this->port) or die("Sorry. Could not connect to Database Server");
     if (!$this->link) {
         $this->errnum = mysqli_errno($this->link);
         $this->error = mysqli_error($this->link);
         $this->error_flag = 1;
         return false;
     }
     if (!@mysqli_select_db($this->link, $this->database)) {
         $this->errnum = mysqli_errno($this->link);
         $this->error = mysqli_error($this->link);
         $this->error_flag = 1;
         die("Cannot connect to database " . $this->database . " for user " . $this->username . "\nError no: " . $this->errnum . "\nError: " . $this->error);
     }
     return true;
 }
Пример #18
0
function getDbLink() {
    if (file_exists(CONFIG_INI) ) {
        $conf = parse_ini_file(CONFIG_INI,true);
        if ( $conf !=false ) {
            if (isset($conf[gethostname()])) {
                $ops = $conf[gethostname()];
                $link = mysqli_init();
                mysqli_real_connect($link, $ops["db_host"], $ops["db_user"], $ops["db_pass"], $ops["db_name"], $ops["db_port"]);
                mysqli_set_charset($link, $ops["db_charset"]);
                mysqli_options($link, MYSQLI_OPT_CONNECT_TIMEOUT, $ops["db_timeout"]);
                return $link; 
            } else {
                return null;
            }
        } else {
            return null;
        }
    } else {
        return null;
    }
}
Пример #19
0
 /**
  * Initialize MySQLi, and Memcache This is the first method called by the
  * application. It checks for the existence of a valid database connection
  * and if memcache exists on the hosts we specified. If the mysql host
  * fails, the application will fail. If a memcache host does not respond,
  * memcache will be disabled for this session.
  *
  * @return void
  */
 private function initDB()
 {
     // use master, slave1, slave2, etc.
     // Step 1: Bring up Master.
     $this->facebookQuery = false;
     $this->db = mysqli_init() or $this->deadError(config::APP_NAME . " is currently undergoing maintenance. Please check back. Stage: init");
     mysqli_options($this->db, MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 1') or $this->deadError(config::APP_NAME . " is currently undergoing maintenance. Please check back. Stage: Command");
     mysqli_options($this->db, MYSQLI_OPT_CONNECT_TIMEOUT, 5) or $this->deadError(config::APP_NAME . " is currently undergoing maintenance. Please check back. Stage: Timeout");
     mysqli_real_connect($this->db, config::$DB_HOST, config::$DB_USER, config::$DB_PASS, config::$DB_DB) or $this->deadError(config::APP_NAME . " is currently undergoing maintenance. Please check back. Stage: Connect");
     // Master is started. Lets start up any slaves.
     if (config::$USE_SLAVES == true) {
         $sc = 0;
         foreach (config::$dbSlaves as $slave) {
             $sc++;
             $obj = "db" . $sc;
             $this->{$obj} = mysqli_init() or $this->deadError(config::APP_NAME . " is currently undergoing maintenance. Please check back. Stage: Slave_init");
             mysqli_options($this->{$obj}, MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 1') or $this->deadError(config::APP_NAME . " is currently undergoing maintenance. Please check back. Stage: Slave_Command");
             mysqli_options($this->{$obj}, MYSQLI_OPT_CONNECT_TIMEOUT, 5) or $this->deadError(config::APP_NAME . " is currently undergoing maintenance. Please check back. Stage: Slave_Timeout");
             mysqli_real_connect($this->{$obj}, config::$DB_HOST, config::$DB_USER, config::$DB_PASS, config::$DB_DB) or $this->deadError(config::APP_NAME . " is currently undergoing maintenance. Please check back. Stage: Slave_Connect");
         }
         $this->slaveCount = $sc;
     }
 }
Пример #20
0
 /**
  */
 function insert_data_with_sql($data = [])
 {
     if (!$data) {
         return false;
     }
     $conf = $this->default_conf;
     foreach ($this->conf as $k => $v) {
         $conf[$k] = $v;
     }
     $db = mysqli_init();
     mysqli_options($db, MYSQLI_OPT_CONNECT_TIMEOUT, $conf['timeout']);
     mysqli_real_connect($db, $conf['db_host'], $conf['db_user'], $conf['db_pswd'], $conf['db_name'], $conf['db_port']);
     mysqli_set_charset($db, 'utf8');
     mysqli_select_db($db, $conf['db_name']);
     // TODO: create separate db connection for this
     // !!! DO not use insert_safe here, it cannot check fields for existance in turbosms and SMS will NOT send
     $sql = str_replace('INSERT INTO `' . DB_PREFIX . $conf['db_name'] . '`', 'INSERT INTO `' . $conf['db_name'] . '`', db()->insert($conf['db_name'], db()->es($data), $as_sql = true));
     $result = mysqli_query($db, $sql);
     if (DEBUG_MODE) {
         debug(__FUNCTION__ . '[]', ['result' => (int) $result, 'data' => $data]);
     }
     mysqli_close($db);
     return $result;
 }
Пример #21
0
 /**
  * connects to the database server
  *
  * @param string $user                 mysql user name
  * @param string $password             mysql user password
  * @param bool   $is_controluser       whether this is a control user connection
  * @param array  $server               host/port/socket/persistent
  * @param bool   $auxiliary_connection (when true, don't go back to login if
  *                                     connection fails)
  *
  * @return mixed false on error or a mysqli object on success
  */
 public function connect($user, $password, $is_controluser = false, $server = null, $auxiliary_connection = false)
 {
     global $cfg;
     $server_port = $GLOBALS['dbi']->getServerPort($server);
     if ($server_port === null) {
         $server_port = 0;
     }
     $server_socket = $GLOBALS['dbi']->getServerSocket($server);
     if ($server) {
         $server['host'] = empty($server['host']) ? 'localhost' : $server['host'];
     }
     // NULL enables connection to the default socket
     $link = mysqli_init();
     mysqli_options($link, MYSQLI_OPT_LOCAL_INFILE, true);
     $client_flags = 0;
     /* Optionally compress connection */
     if ($cfg['Server']['compress'] && defined('MYSQLI_CLIENT_COMPRESS')) {
         $client_flags |= MYSQLI_CLIENT_COMPRESS;
     }
     /* Optionally enable SSL */
     if ($cfg['Server']['ssl'] && defined('MYSQLI_CLIENT_SSL')) {
         mysqli_ssl_set($link, $cfg['Server']['ssl_key'], $cfg['Server']['ssl_cert'], $cfg['Server']['ssl_ca'], $cfg['Server']['ssl_ca_path'], $cfg['Server']['ssl_ciphers']);
         $ssl_flag = MYSQLI_CLIENT_SSL;
         /*
          * disables SSL certificate validation on mysqlnd for MySQL 5.6 or later
          * @link https://bugs.php.net/bug.php?id=68344
          * @link https://github.com/phpmyadmin/phpmyadmin/pull/11838
          */
         if (!$cfg['Server']['ssl_verify'] && defined('MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT')) {
             $ssl_flag = MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT;
         }
         $client_flags |= $ssl_flag;
     }
     if (!$server) {
         $return_value = @$this->_realConnect($link, $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 = @$this->_realConnect($link, $cfg['Server']['host'], $user, '', false, $server_port, $server_socket, $client_flags);
         }
     } else {
         $return_value = @$this->_realConnect($link, $server['host'], $user, $password, false, $server_port, $server_socket);
     }
     if ($return_value === false) {
         return false;
     }
     return $link;
 }
 /**
  * connects to the database server
  *
  * @param string $user                 mysql user name
  * @param string $password             mysql user password
  * @param bool   $is_controluser       whether this is a control user connection
  * @param array  $server               host/port/socket/persistent
  * @param bool   $auxiliary_connection (when true, don't go back to login if
  *                                     connection fails)
  *
  * @return mixed false on error or a mysqli object on success
  */
 public function connect($user, $password, $is_controluser = false, $server = null, $auxiliary_connection = false)
 {
     global $cfg;
     $server_port = $GLOBALS['dbi']->getServerPort($server);
     $server_socket = $GLOBALS['dbi']->getServerSocket($server);
     if ($server) {
         $server['host'] = empty($server['host']) ? 'localhost' : $server['host'];
     }
     // NULL enables connection to the default socket
     $link = mysqli_init();
     mysqli_options($link, MYSQLI_OPT_LOCAL_INFILE, true);
     $client_flags = 0;
     /* Optionally compress connection */
     if ($cfg['Server']['compress'] && defined('MYSQLI_CLIENT_COMPRESS')) {
         $client_flags |= MYSQLI_CLIENT_COMPRESS;
     }
     /* Optionally enable SSL */
     if ($cfg['Server']['ssl'] && defined('MYSQLI_CLIENT_SSL')) {
         mysqli_ssl_set($link, $cfg['Server']['ssl_key'], $cfg['Server']['ssl_cert'], $cfg['Server']['ssl_ca'], $cfg['Server']['ssl_ca_path'], $cfg['Server']['ssl_ciphers']);
         $client_flags |= MYSQLI_CLIENT_SSL;
     }
     if (!$server) {
         $return_value = @$this->_realConnect($link, $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 = @$this->_realConnect($link, $cfg['Server']['host'], $user, '', false, $server_port, $server_socket, $client_flags);
         }
     } else {
         $return_value = @$this->_realConnect($link, $server['host'], $user, $password, false, $server_port, $server_socket);
     }
     if ($return_value === false) {
         return false;
     }
     return $link;
 }
<?php

/*
Load local file into the database table.
Please define the table cloumn in CREATE TABLE section.
The column order must be same as the one in the local file. 
*/
// Parameter set
$database_name = "<database name here>";
$table_name = "<table name here>";
$load_file = "<filename here>";
$user = "";
$pass = "";
$server = "";
// Database connection
$link = mysqli_init();
mysqli_options($link, MYSQLI_OPT_LOCAL_INFILE, true);
mysqli_real_connect($link, $server, $user, $pass, $database_name);
// Table drop
$sql = "DROP TABLE IF EXISTS `" . $table_name . "`;";
mysqli_query($link, $sql) or die(mysqli_error($enllac));
// Table create
// Here are the sample columns.
$sql = "CREATE TABLE `" . $table_name . "` (\r\n\t  `service_id` varchar(45) DEFAULT NULL,\r\n\t  `product_type` varchar(45) DEFAULT NULL,\r\n\t  `product_line` varchar(45) DEFAULT NULL,\r\n\t  `product_name` varchar(45) DEFAULT NULL,\r\n\t  `status` varchar(45) DEFAULT NULL,\r\n\t  `account` varchar(45) DEFAULT NULL,\r\n\t  `billing_start_date` varchar(45) DEFAULT NULL,\r\n\t  `billing_end_date` varchar(45) DEFAULT NULL,\r\n\t  `mrc_subtotal` int(11) DEFAULT NULL,\r\n\t  `nrc_subtotal` int(11) DEFAULT NULL,\r\n\t  `quantity` int(11) DEFAULT NULL\r\n\t) ENGINE=InnoDB DEFAULT CHARSET=latin1;";
mysqli_query($link, $sql) or die(mysqli_error($enllac));
// Load local data
$sql = "LOAD DATA LOCAL INFILE '" . $load_file . "' INTO TABLE `" . $table_name . "`\r\n\tFIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\r' IGNORE 1 LINES;";
mysqli_query($link, $sql) or die(mysqli_error($enllac));
Пример #24
0
 /**
  * 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'");
     }
 }
Пример #25
0
 /**
  * Connects to a database.
  * @return void
  * @throws DibiException
  */
 public function connect(array &$config)
 {
     mysqli_report(MYSQLI_REPORT_OFF);
     if (isset($config['resource'])) {
         $this->connection = $config['resource'];
     } else {
         // default values
         if (!isset($config['charset'])) {
             $config['charset'] = 'utf8';
         }
         if (!isset($config['username'])) {
             $config['username'] = ini_get('mysqli.default_user');
         }
         if (!isset($config['password'])) {
             $config['password'] = ini_get('mysqli.default_pw');
         }
         if (!isset($config['socket'])) {
             $config['socket'] = ini_get('mysqli.default_socket');
         }
         if (!isset($config['port'])) {
             $config['port'] = NULL;
         }
         if (!isset($config['host'])) {
             $host = ini_get('mysqli.default_host');
             if ($host) {
                 $config['host'] = $host;
                 $config['port'] = ini_get('mysqli.default_port');
             } else {
                 $config['host'] = NULL;
                 $config['port'] = NULL;
             }
         }
         $foo =& $config['flags'];
         $foo =& $config['database'];
         $this->connection = mysqli_init();
         if (isset($config['options'])) {
             if (is_scalar($config['options'])) {
                 $config['flags'] = $config['options'];
                 // back compatibility
                 trigger_error(__CLASS__ . ": configuration item 'options' must be array; for constants MYSQLI_CLIENT_* use 'flags'.", E_USER_NOTICE);
             } else {
                 foreach ((array) $config['options'] as $key => $value) {
                     mysqli_options($this->connection, $key, $value);
                 }
             }
         }
         @mysqli_real_connect($this->connection, $config['host'], $config['username'], $config['password'], $config['database'], $config['port'], $config['socket'], $config['flags']);
         // intentionally @
         if ($errno = mysqli_connect_errno()) {
             throw new DibiDriverException(mysqli_connect_error(), $errno);
         }
     }
     if (isset($config['charset'])) {
         $ok = FALSE;
         if (version_compare(PHP_VERSION, '5.1.5', '>=')) {
             // affects the character set used by mysql_real_escape_string() (was added in MySQL 5.0.7 and PHP 5.0.5, fixed in PHP 5.1.5)
             $ok = @mysqli_set_charset($this->connection, $config['charset']);
             // intentionally @
         }
         if (!$ok) {
             $this->query("SET NAMES '{$config['charset']}'");
         }
     }
     if (isset($config['sqlmode'])) {
         $this->query("SET sql_mode='{$config['sqlmode']}'");
     }
     $this->query("SET time_zone='" . date('P') . "'");
     $this->buffered = empty($config['unbuffered']);
 }
Пример #26
0
 /**
  * Creates a connection to the database.
  *
  * @return void
  * @throws Zend_Db_Adapter_Mysqli_Exception
  */
 protected function _connect()
 {
     if ($this->_connection) {
         return;
     }
     if (!extension_loaded('mysqli')) {
         /**
          * @see Zend_Db_Adapter_Mysqli_Exception
          */
         //require_once 'Zend/Db/Adapter/Mysqli/Exception.php';
         throw new Zend_Db_Adapter_Mysqli_Exception('The Mysqli extension is required for this adapter but the extension is not loaded');
     }
     if (isset($this->_config['port'])) {
         $port = (int) $this->_config['port'];
     } else {
         $port = null;
     }
     if (isset($this->_config['socket'])) {
         $socket = $this->_config['socket'];
     } else {
         $socket = null;
     }
     $this->_connection = mysqli_init();
     if (!empty($this->_config['driver_options'])) {
         foreach ($this->_config['driver_options'] as $option => $value) {
             if (is_string($option)) {
                 // Suppress warnings here
                 // Ignore it if it's not a valid constant
                 $option = @constant(strtoupper($option));
                 if ($option === null) {
                     continue;
                 }
             }
             mysqli_options($this->_connection, $option, $value);
         }
     }
     // Suppress connection warnings here.
     // Throw an exception instead.
     $_isConnected = @mysqli_real_connect($this->_connection, $this->_config['host'], $this->_config['username'], $this->_config['password'], $this->_config['dbname'], $port, $socket);
     if ($_isConnected === false || mysqli_connect_errno()) {
         $this->closeConnection();
         /**
          * @see Zend_Db_Adapter_Mysqli_Exception
          */
         //require_once 'Zend/Db/Adapter/Mysqli/Exception.php';
         throw new Zend_Db_Adapter_Mysqli_Exception(mysqli_connect_error());
     }
     if (!empty($this->_config['charset'])) {
         mysqli_set_charset($this->_connection, $this->_config['charset']);
     }
 }
 if (!mysqli_query($link, sprintf("INSERT INTO test(id) VALUES (%f)", $data[1]))) {
     printf("[005] [%d] %s\n", mysqli_errno($link), mysqli_error($link));
     continue;
 }
 if (!($res = mysqli_query($link, "SELECT id FROM test"))) {
     printf("[006] [%d] %s\n", mysqli_errno($link), mysqli_error($link));
     continue;
 }
 $row = mysqli_fetch_assoc($res);
 mysqli_free_result($res);
 if ($row['id'] !== $data[1]) {
     printf("[007] Expecting %s - %s/%s got %s/%s\n", $name, $data[1], gettype($data[1]), $row['id'], gettype($row['id']));
 }
 mysqli_close($link);
 $link = mysqli_init();
 if (!mysqli_options($link, MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 0)) {
     printf("[008] [%d] %s\n", mysqli_errno($link), mysqli_error($link));
     continue;
 }
 if (!my_mysqli_real_connect($link, $host, $user, $passwd, $db, $port, $socket)) {
     printf("[009] [%d] %s\n", mysqli_connect_errno(), mysqli_connect_error());
     continue;
 }
 if (!($res = mysqli_query($link, "SELECT id FROM test"))) {
     printf("[010] [%d] %s\n", mysqli_errno($link), mysqli_error($link));
     continue;
 }
 $row = mysqli_fetch_assoc($res);
 mysqli_free_result($res);
 if (!is_string($row['id']) || $row['id'] != $data[1]) {
     printf("[011] Expecting %s - %s/string got %s/%s\n", $name, $data[1], $row['id'], gettype($row['id']));
Пример #28
0
 /**
  * @ignore
  */
 private function connect($is_master = true)
 {
     if ($this->port == 0) {
         $this->error = 13048;
         $this->errno = 'Not Initialized';
         return false;
     }
     if ($is_master) {
         $host = 'w' . $this->host;
     } else {
         $host = 'r' . $this->host;
     }
     //edit by biner
     $host = $this->host;
     $db = mysqli_init();
     mysqli_options($db, MYSQLI_OPT_CONNECT_TIMEOUT, 5);
     if (!mysqli_real_connect($db, $host, $this->accesskey, $this->secretkey, $this->appname, $this->port)) {
         $this->error = mysqli_connect_error();
         $this->errno = mysqli_connect_errno();
         return false;
     }
     mysqli_set_charset($db, $this->charset);
     return $db;
 }
Пример #29
0
 /**
  * Apply the driver options to the connection.
  *
  * @param array $driverOptions
  *
  * @throws MysqliException When one of of the options is not supported.
  * @throws MysqliException When applying doesn't work - e.g. due to incorrect value.
  */
 private function setDriverOptions(array $driverOptions = array())
 {
     $supportedDriverOptions = array(\MYSQLI_OPT_CONNECT_TIMEOUT, \MYSQLI_OPT_LOCAL_INFILE, \MYSQLI_INIT_COMMAND, \MYSQLI_READ_DEFAULT_FILE, \MYSQLI_READ_DEFAULT_GROUP);
     if (defined('MYSQLI_SERVER_PUBLIC_KEY')) {
         $supportedDriverOptions[] = \MYSQLI_SERVER_PUBLIC_KEY;
     }
     $exceptionMsg = "%s option '%s' with value '%s'";
     foreach ($driverOptions as $option => $value) {
         if ($option === static::OPTION_FLAGS) {
             continue;
         }
         if (!in_array($option, $supportedDriverOptions, true)) {
             throw new MysqliException(sprintf($exceptionMsg, 'Unsupported', $option, $value));
         }
         if (@mysqli_options($this->_conn, $option, $value)) {
             continue;
         }
         $msg = sprintf($exceptionMsg, 'Failed to set', $option, $value);
         $msg .= sprintf(', error: %s (%d)', mysqli_error($this->_conn), mysqli_errno($this->_conn));
         throw new MysqliException($msg, $this->_conn->sqlstate, $this->_conn->errno);
     }
 }
Пример #30
0
 public function executeSQL($query, &$resultArry, &$rowsAffected, $assoc = TRUE)
 {
     $l_iTries = 3;
     //times
     $l_iPause = 2;
     //seconds
     $l_bConnected = FALSE;
     //bool
     do {
         $link = mysqli_init();
         $rowsAffected = 0;
         if (!$link) {
             throw new DBAdapter2Exception("mysqli_init failed");
         }
         if (!mysqli_options($link, MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
             throw new DBAdapter2Exception("Setting MYSQLI_OPT_CONNECT_TIMEOUT failed");
         }
         if (!mysqli_real_connect($link, $this->host, $this->username, $this->password, $this->schema)) {
             unset($link);
             sleep($l_iPause);
             $l_iTries = $l_iTries - 1;
         } else {
             $l_bConnected = TRUE;
             $l_iTries = 0;
         }
     } while (!$l_bConnected && $l_iTries > 0);
     if (!$l_bConnected) {
         throw new DBAdapter2Exception('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
     }
     if (!mysqli_set_charset($link, $this->charset)) {
         throw new DBAdapter2Exception('Error loading character set ' . $this->charset . ' - ' . mysqli_error($link));
     }
     //do queries
     if (mysqli_real_query($link, $query)) {
         //should be e proper select
         if (mysqli_field_count($link)) {
             //buffered
             $result = mysqli_store_result($link);
             if ($result) {
                 $resultArry = array();
                 $rowsAffected = mysqli_num_rows($result);
                 if ($assoc) {
                     while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
                         $resultArry[] = $row;
                     }
                 } else {
                     while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
                         $resultArry[] = $row;
                     }
                 }
                 mysqli_free_result($result);
                 unset($result);
             }
         }
     } else {
         throw new DBAdapter2Exception('Error in query: ' . mysqli_error($link));
     }
     mysqli_close($link);
 }