public function open($save_path, $session_id) { if ($this->connection === null) { $this->connection = new \mysqli($this->config['host'], $this->config['user'], $this->config['pass']); $this->connection->select_db($this->config['database']); } }
public function __construct() { $this->conn = mysqli_connect(config::val("db_ip"), config::val("db_user"), config::val("db_pass")) or die("mysqli_connect 1"); $this->create_database(); $this->conn->select_db("smarttable"); $this->create_tables(); }
function opendatabase($dataname) { global $inifile; //Connection pointer to sql $sqlc = new mysqli($inifile["conndet"]["server"], $inifile["conndet"]["user"], $inifile["conndet"]["pass"]); //Checking if connection is good if ($sqlc->connect_errno) { return errlog("Error: " . $sqlc->connect_errno . " Failed to connect to server " . $inifile["conndet"]["server"] . "."); } //attempting to open database if (!$sqlc->select_db($dataname)) { //If connection fails run this //If autocreate is false if (!$inifile["mysqlval"]["autocreate"]) { return errlog("Database {$dataname} does not exist."); } else { //If not create new one errlog("Database does not exist. Creating database {$dataname}"); //Checking if new data base was created if (!$sqlc->query('CREATE DATABASE ' . $dataname)) { //If not then log failed return errlog("Error: " . $sqlc->error . " Failed to create database: {$dataname}"); } else { $sqlc->select_db($dataname); } return $sqlc; } } else { //Conncetion succeeded return $sqlc; } }
/** * Set the database. * * @param string $db * @return bool success */ public function setDatabase($db) { if ($this->conn->connect_error) { return false; } return @$this->conn->select_db($db); }
/** * This method makes sure to connect to the database properly * * @param string $strHost * @param string $strUsername * @param string $strPass * @param string $strDbName * @param int $intPort * * @return bool * @throws class_exception */ public function dbconnect($strHost, $strUsername, $strPass, $strDbName, $intPort) { if ($intPort == "") { $intPort = "3306"; } //save connection-details $this->strHost = $strHost; $this->strUsername = $strUsername; $this->strPass = $strPass; $this->strDbName = $strDbName; $this->intPort = $intPort; $this->linkDB = @new mysqli($strHost, $strUsername, $strPass, $strDbName, $intPort); if ($this->linkDB !== false) { if (@$this->linkDB->select_db($strDbName)) { //erst ab mysql-client-bib > 4 //mysqli_set_charset($this->linkDB, "utf8"); $this->_pQuery("SET NAMES 'utf8'", array()); $this->_pQuery("SET CHARACTER SET utf8", array()); $this->_pQuery("SET character_set_connection ='utf8'", array()); $this->_pQuery("SET character_set_database ='utf8'", array()); $this->_pQuery("SET character_set_server ='utf8'", array()); return true; } else { throw new class_exception("Error selecting database", class_exception::$level_FATALERROR); } } else { throw new class_exception("Error connecting to database", class_exception::$level_FATALERROR); } }
/** * @see Lumine_Connection_IConnection::connect() */ public function connect() { if ($this->conn && $this->state == self::OPEN) { Lumine_Log::debug('Utilizando conexao cacheada com ' . $this->getDatabase()); $this->conn->select_db($this->getDatabase()); return true; } $this->dispatchEvent(new Lumine_Events_ConnectionEvent(Lumine_Event::PRE_CONNECT, $this)); $hostString = $this->getHost(); if ($this->getPort() != '') { $hostString .= ':' . $this->getPort(); } if (isset($this->options['socket']) && $this->options['socket'] != '') { $hostString .= ':' . $this->options['socket']; } $flags = isset($this->options['flags']) ? $this->options['flags'] : null; if (isset($this->options['persistent']) && $this->options['persistent'] == true) { $hostString = 'p:' . $hostString; } Lumine_Log::debug('Criando conexao com ' . $this->getDatabase()); $this->conn = new mysqli($this->getHost(), $this->getUser(), $this->getPassword(), $this->getDatabase()); if ($this->conn->connect_error) { $this->state = self::CLOSED; $msg = 'nao foi possivel conectar no banco de dados: ' . $this->getDatabase() . ' - ' . $this->conn->connect_error; Lumine_Log::error($msg); $this->dispatchEvent(new Lumine_Events_ConnectionEvent(Lumine_Event::CONNECTION_ERROR, $this, $msg)); throw new Exception($msg); return false; } // seleciona o banco $this->state = self::OPEN; $this->setCharset($this->getCharset()); $this->dispatchEvent(new Lumine_Events_ConnectionEvent(Lumine_Event::POS_CONNECT, $this)); return true; }
/** * Changes current database * @param string $database database name * @return boolean true on success, false - otherwise */ public function changeDb($database) { if ($this->conn->select_db($database)) { return true; } return false; }
/** * connect database */ public function open() { if ($this->connection === null) { $this->driver = new \mysqli_driver(); $this->driver->report_mode = MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT; $this->connection = new \mysqli($this->config['host'], $this->config['user'], $this->config['pass']); $this->connection->select_db($this->config['database']); } }
/** * Реализация установки соединения с базой * @throws Exception */ protected function realConnect() { $this->db = @new \mysqli(!empty($this->config['hostname']) ? 'p:' . $this->config['hostname'] : '', $this->config['username'], $this->config['password']); if ($this->db->connect_error) { throw new Exception($this->error = $this->db->connect_error); } $this->db->set_charset('utf8'); if (!$this->db->select_db($this->config['database'])) { throw new Exception($this->error = $this->db->error); } }
/** begins the MySQL connection * @param bool $create_db * @throws DBMySQLException */ private function init_mysql_connect($create_db = FALSE) { $this->connect = new mysqli($this->host, $this->user, $this->pass, NULL, $this->port); if ($this->connect->connect_errno > 0) { throw new DBMySQLException('Unable to connect to MySQL server reason: ' . $this->connect->connect_error, 1); } $this->connect->set_charset($this->encoding); if ($create_db) { $this->connect->query('CREATE DATABASE IF NOT EXISTS ' . $this->format_table_or_database_string($this->db_name)); } $this->connect->select_db($this->db_name); }
function vConnectDB($sDBName) { global $mysqli; ##$mysqli = new mysqli( "localhost", "root", "John0316", "test" ); $mysqli = new mysqli("p:localhost", "root", "bb4587", "baboom"); // p: stands for persistent DB connection. // When there is too many connections, this can lower the // overhead. However, extra server has to be increased right away // because it can create DB connection error or DB table lock. (12-26-14) ###### # 12-12-14 Gets the error number of the connection. ###### #if (mysqli_connect_errno()) if ($mysqli->connect_errno) { printf("Connect failed: %s\n", $mysqli->connect_errno); exit; } ####### # 12-12-14 Now use a database. If the DB doesn't exists, exit out # of the program. ####### $bResult = $mysqli->select_db($sDBName); if ($bResult == FALSE) { printf("{$sDBName} database doesn't exists. \n"); exit; } }
function db_connect() { global $MYSQL_HOST; global $MYSQL_USER; global $MYSQL_PASS; $mysqli = new mysqli($MYSQL_HOST, $MYSQL_USER, $MYSQL_PASS); if ($mysqli->connect_errno) { print "<b>Failed to connect to MySQL: " . $mysqli->connect_error . "</b><br/>\n"; return FALSE; } if ($mysqli->select_db("trees") === FALSE) { print "<b>select_db() failed</b><br/>\n"; $mysqli->close(); return FALSE; } $result = $mysqli->query("SELECT DATABASE()"); if ($result !== FALSE) { $row = $result->fetch_row(); if ($row[0] != "trees") { print "<b>Unable to select database</b><br/>\n"; $mysqli->close(); return FALSE; } } else { print "<b>SELECT DATABASE() failed</b><br/>\n"; $mysqli->close(); return FALSE; } return $mysqli; }
function modificaCoche($coche) { //alert($coche->login); global $servidor, $bd, $usuario, $contrasenia; try { @($db = new mysqli($servidor, $usuario, $contrasenia)); if (mysqli_connect_errno() != 0) { throw new Exception('Error conectando:' . mysqli_connect_error(), mysqli_connect_errno()); } $db->select_db($bd); if ($db->errno != 0) { throw new Exception('Error seleccionando bd:' . $db->error, $db->errno); } $consulta = "update coches set marca='" . $coche->marca . "', modelo='" . $coche->modelo . "', color='" . $coche->color . "' where matricula='" . $coche->matricula . "'"; if ($db->query($consulta) === false) { throw new ExcepcionEnTransaccion(); } $db->commit(); $db->close(); } catch (ExcepcionEnTransaccion $e) { echo 'No se ha podido realizar la modificacion'; $db->rollback(); $db->close(); } catch (Exception $e) { echo $e->getMessage(); if (mysqli_connect_errno() == 0) { $db->close(); } exit; } }
private function step3() { $mysqli = new mysqli("localhost", 'root', ''); $mysqli->select_db("kongcms"); $mysqli->query("set names utf8"); //Tools::dump($mysqli); if (isset($_POST['send'])) { $sql = "update admin \r\n\t\t\t\t set username='******'admin_user'] . "',\r\n\t\t\t\t pwd='" . md5($_POST['admin_pwd']) . "',\r\n\t\t\t\t\t last_ip='" . $_SERVER['REMOTE_ADDR'] . "',\r\n\t\t\t\t\t last_time=now(),\r\n\t\t\t\t\t login_num=1,\r\n\t\t\t\t\t reg_time=now()\r\n\t\t\t\t where username='******'"; /* $sql="insert into admin( username, pwd, last_ip, last_time, login_num, level_id, reg_time )values( '".$_POST['admin_user']."', '".md5($_POST['admin_pwd'])."', '".$_SERVER['REMOTE_ADDR']."', now(), 1, 3, now() )"; */ if ($mysqli->query($sql)) { Tools::Redirect("后台管理员添加成功", "?a=install&action=step4"); } else { Tools::Redirect("后台管理员添加失败", "?a=install&action=step3"); } } $this->smarty->assign("step3", true); }
public function __construct() { $config = App::$config['database']; $db = new mysqli($config['server'], $config['username'], $config['password']); $db->select_db($config['database']); $this->db = $db; }
public function connection() { $con = new mysqli($this->host, $this->user, $this->pass); $con->select_db($this->database); $con->set_charset($this->charset); return $con; }
function connect($database, $query) { // set constants $host = SERVER; $port = 3306; $socket = ""; $user = USERNAME; $password = PASSWORD; $dbname = $database; // open connection to mysql $con = new mysqli($host, $user, $password, $dbname, $port, $socket) or die('Could not connect to the database server' . mysqli_connect_error()); // test connection to MySQL if (!$con) { die('Connection failed: ' . mysqli_error()); } else { echo "connected successfully" . "<br>"; } // select a database $con->select_db($database); // query the database $results = $con->query($query); // check if query successful if (!$results) { echo "query failed" . "<br>"; } else { echo "query successful" . "<br>"; } // close the MySQl connection $con->close(); return $results; }
function modificaAlumno($alumno) { global $servidor, $bd, $usuario, $contrasenia; try { @($db = new mysqli($servidor, $usuario, $contrasenia)); if (mysqli_connect_errno() != 0) { throw new Exception('Error conectando:' . mysqli_connect_error(), mysqli_connect_errno()); } $db->select_db($bd); if ($db->errno != 0) { throw new Exception('Error seleccionando bd:' . $db->error, $db->errno); } $consulta = "update alumnos set password='******', nombre='" . $alumno->nombre . "', apellido='" . $alumno->apellido . "', dni='" . $alumno->dni . "', email='" . $alumno->email . "', telefono=" . $alumno->telefono . ", sexo='" . $alumno->sexo . "' where login='******'"; if ($db->query($consulta) === false) { throw new ExcepcionEnTransaccion(); } $db->commit(); $db->close(); } catch (ExcepcionEnTransaccion $e) { echo 'No se ha podido realizar la modificacion'; $db->rollback(); $db->close(); } catch (Exception $e) { echo $e->getMessage(); if (mysqli_connect_errno() == 0) { $db->close(); } exit; } }
function get_mysql_connection() { $conn = new mysqli("localhost", "USERNAME", "PASSWORD") or die("Database error."); $conn->select_db("CrisisTracker"); $conn->set_charset("utf8"); return $conn; }
public static function db_connect() { $mysqli= new mysqli("localhost","adrianet_admin","admin"); $mysqli->select_db("adrianet_admin"); return $mysqli; }
public function Init() { $link = new mysqli($this->dbhost, $this->dbuser, $this->dbpwd); if ($link->connect_errno) { printf("<div id='alert'>Connection to Host: %s failed! Error: %s</div>", $this->dbhost, $link->connect_error); return false; } if ($_SERVER['SERVER_NAME'] == "127.0.0.1" || $_SERVER['SERVER_NAME'] == "localhost") { $link->query("CREATE DATABASE IF NOT EXISTS {$this->dbname} CHARACTER SET = 'utf8'"); if ($link->error) { printf("<div id='alert'>Error: %s</div>", $link->error); die("End"); } /*else { echo "result $result DATABASE $this->dbname CREATED!<br>"; }*/ $link->select_db($this->dbname); if ($link->error) { printf("<div id='alert'>Error: %s</div>", $link->error); return false; } foreach ($this->dbtbles as $value) { $link->query($value[1]); if ($link->error) { printf("Error: %s<br>", $link->error); return false; } /*echo "result $result Table ".$value[0]." created!<br>";*/ } } return true; }
static function createConfig($host = 'localhost', $user, $password, $name = 'lychee', $prefix = '') { # Check dependencies Module::dependencies(isset($host, $user, $password, $name)); $database = new mysqli($host, $user, $password); if ($database->connect_errno) { return 'Warning: Connection failed!'; } # Check if database exists if (!$database->select_db($name)) { # Database doesn't exist # Check if user can create the database $result = Database::createDatabase($database, $name); if ($result === false) { return 'Warning: Creation failed!'; } } # Escape data $host = mysqli_real_escape_string($database, $host); $user = mysqli_real_escape_string($database, $user); $password = mysqli_real_escape_string($database, $password); $name = mysqli_real_escape_string($database, $name); $prefix = mysqli_real_escape_string($database, $prefix); # Save config.php $config = "<?php\n\n###\n# @name\t\t\tConfiguration\n# @author\t\tTobias Reich\n# @copyright\t2014 Tobias Reich\n###\n\nif(!defined('LYCHEE')) exit('Error: Direct access is not allowed!');\n\n# Database configuration\n\$dbHost = '{$host}'; # Host of the database\n\$dbUser = '******'; # Username of the database\n\$dbPassword = '******'; # Password of the database\n\$dbName = '{$name}'; # Database name\n\$dbTablePrefix = '{$prefix}'; # Table prefix\n\$lang = 'en'; # Language\n\n?>"; # Save file if (file_put_contents(LYCHEE_CONFIG_FILE, $config) === false) { return 'Warning: Could not create file!'; } return true; }
function connect($name, $path = false) { $this->name = $name; global $cfg; $link = new mysqli($cfg->mysqli_host, $cfg->mysqli_username, $cfg->mysqli_password); // Make sure database exists $res = $link->query("SHOW DATABASES"); while ($row = $res->fetch_row()) { if ($row[0] == $name) { $do = true; } } if (!isset($do)) { $do = false; } if (!$do) { $link->query("CREATE DATABASE {$name}"); } $link->select_db($name); // check connection if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit; } $this->link = $link; return $link; }
function findEmptyKey($table, $column) { $j = false; @($db = new mysqli('localhost', getDBUserName(0), getDBPassword(0), getDBName(0))); if (mysqli_connect_errno()) { //echo "<p>Errorrrss</p>"; exit; } else { $db->select_db("UMBRELLA"); $query = "select " . $column . " from " . $table; $result = $db->query($query); $num_result = $result->num_rows; $d = array(); for ($i = 0; $i < $num_result; $i++) { $row = $result->fetch_assoc(); //echo "<p>".$row[$column]."</p>"; $d[$i] = $row[$column]; } //echo "<p>Number of results: ".$num_result."</p>"; sort($d); for ($z = 0; $z < $num_result; $z++) { if ($z != $d[$z]) { $j = $z; break; } } if ($j == false) { $j = count($d); } } $db->close(); return $j; }
function EXPORT_TABLES($host, $user, $pass, $name, $tables = false, $backup_name = false) { $mysqli = new mysqli($host, $user, $pass, $name); $mysqli->select_db($name); $mysqli->query("SET NAMES 'utf8'"); $queryTables = $mysqli->query('SHOW TABLES'); while ($row = $queryTables->fetch_row()) { $target_tables[] = $row[0]; } if ($tables !== false) { $target_tables = array_intersect($target_tables, $tables); } $content = "SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\r\nSET time_zone = \"+00:00\";\r\n\r\n\r\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\r\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\r\n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\r\n/*!40101 SET NAMES utf8 */;\r\n"; foreach ($target_tables as $table) { $result = $mysqli->query('SELECT * FROM ' . $table); $fields_amount = $result->field_count; $rows_num = $mysqli->affected_rows; // $res = $mysqli->query('SHOW CREATE TABLE ' . $table); // $TableMLine = $res->fetch_row(); $content .= "\n\n"; // $content =""; for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter = 0) { while ($row = $result->fetch_row()) { //when started (and every after 100 command cycle): if ($st_counter % 100 == 0 || $st_counter == 0) { $content .= "\nINSERT INTO " . $table . " VALUES"; } $content .= "\n("; for ($j = 0; $j < $fields_amount; $j++) { $row[$j] = str_replace("\n", "\\n", addslashes($row[$j])); if (isset($row[$j])) { $content .= '"' . $row[$j] . '"'; } else { $content .= '""'; } if ($j < $fields_amount - 1) { $content .= ','; } } $content .= ")"; //every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler if (($st_counter + 1) % 100 == 0 && $st_counter != 0 || $st_counter + 1 == $rows_num) { $content .= ";"; } else { $content .= ","; } $st_counter = $st_counter + 1; } } $content .= "\n\n\n"; } $content .= "\r\n\r\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\r\n/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\r\n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;"; $backup_name = $backup_name ? $backup_name : $name . "___(" . date('H-i-s') . "_" . date('d-m-Y') . ")__rand" . rand(1, 11111111) . ".sql"; header('Content-Type: application/octet-stream'); header("Content-Transfer-Encoding: Binary"); header("Content-disposition: attachment; filename=\"" . $backup_name . "\""); echo $content; exit; }
static function connect_dsn($dsn) { global $Opt; $dbhost = $dbuser = $dbpass = $dbname = $dbport = null; if ($dsn && preg_match('|^mysql://([^:@/]*)/(.*)|', $dsn, $m)) { $dbhost = urldecode($m[1]); $dbname = urldecode($m[2]); } else { if ($dsn && preg_match('|^mysql://([^:@/]*)@([^/]*)/(.*)|', $dsn, $m)) { $dbhost = urldecode($m[2]); $dbuser = urldecode($m[1]); $dbname = urldecode($m[3]); } else { if ($dsn && preg_match('|^mysql://([^:@/]*):([^@/]*)@([^/]*)/(.*)|', $dsn, $m)) { $dbhost = urldecode($m[3]); $dbuser = urldecode($m[1]); $dbpass = urldecode($m[2]); $dbname = urldecode($m[4]); } } } if (!$dbname || $dbname === "mysql" || substr($dbname, -7) === "_schema") { return array(null, null); } $dbsock = @$Opt["dbSocket"]; if ($dbsock && $dbport === null) { $dbport = ini_get("mysqli.default_port"); } if ($dbpass === null) { $dbpass = ini_get("mysqli.default_pw"); } if ($dbuser === null) { $dbuser = ini_get("mysqli.default_user"); } if ($dbhost === null) { $dbhost = ini_get("mysqli.default_host"); } if ($dbsock) { $dblink = new mysqli($dbhost, $dbuser, $dbpass, "", $dbport, $dbsock); } else { if ($dbport !== null) { $dblink = new mysqli($dbhost, $dbuser, $dbpass, "", $dbport); } else { $dblink = new mysqli($dbhost, $dbuser, $dbpass); } } if ($dblink && !mysqli_connect_errno() && $dblink->select_db($dbname)) { $dblink->set_charset("utf8"); // The necessity of the following line is explosively terrible // (the default is 1024/!?))(U#*@$%&!U $dblink->query("set group_concat_max_len=4294967295"); } else { if ($dblink) { $dblink->close(); $dblink = null; } } return array($dblink, $dbname); }
public static function getResource() { if (self::$mysqli == NULL) { $mysqli = new mysqli('localhost', 'root', ''); $mysqli->select_db("socialityplus"); return $mysqli; } }
public function removeDatabase($options) { $mysqli = new \mysqli($options['db_hostname'], $options['db_username'], $options['db_password']); if ($mysqli->select_db($options['db_database'])) { $mysqli->query("drop database " . $options['db_database']); } $mysqli->close(); }
/** * Select the database * * [!!] This is called automatically by [Database_MySQLi::connect]. * * @param string $database Database name * * @throws \Gleez\Database\ConnectionException */ protected function _select_db($database) { if (!$this->_connection->select_db($database)) { // Unable to select database throw new ConnectionException($this->_connection->error, $this->_connection->errno); } static::$_current_databases[$this->_connection_id] = $database; }
function Export_Database($host, $user, $pass, $name, $tables = false, $backup_name = false) { $mysqli = new mysqli($host, $user, $pass, $name); $mysqli->select_db($name); $mysqli->query("SET NAMES 'utf8'"); $queryTables = $mysqli->query('SHOW TABLES'); while ($row = $queryTables->fetch_row()) { $target_tables[] = $row[0]; } if ($tables !== false) { $target_tables = array_intersect($target_tables, $tables); } foreach ($target_tables as $table) { $result = $mysqli->query('SELECT * FROM ' . $table); $fields_amount = $result->field_count; $rows_num = $mysqli->affected_rows; $res = $mysqli->query('SHOW CREATE TABLE ' . $table); $TableMLine = $res->fetch_row(); $content = (!isset($content) ? '' : $content) . "\n\n" . $TableMLine[1] . ";\n\n"; for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter = 0) { while ($row = $result->fetch_row()) { //when started (and every after 100 command cycle): if ($st_counter % 100 == 0 || $st_counter == 0) { $content .= "\nINSERT INTO " . $table . " VALUES"; } $content .= "\n("; for ($j = 0; $j < $fields_amount; $j++) { $row[$j] = str_replace("\n", "\\n", addslashes($row[$j])); if (isset($row[$j])) { $content .= '"' . $row[$j] . '"'; } else { $content .= '""'; } if ($j < $fields_amount - 1) { $content .= ','; } } $content .= ")"; //every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler if (($st_counter + 1) % 100 == 0 && $st_counter != 0 || $st_counter + 1 == $rows_num) { $content .= ";"; } else { $content .= ","; } $st_counter = $st_counter + 1; } } $content .= "\n\n\n"; } //$backup_name = $backup_name ? $backup_name : $name."___(".date('H-i-s')."_".date('d-m-Y').")__rand".rand(1,11111111).".sql"; $backup_name = $backup_name ? $backup_name : $name . ".sql"; // header('Content-Type: application/octet-stream'); // header("Content-Transfer-Encoding: Binary"); // header("Content-disposition: attachment; filename=\"".$backup_name."\""); return $content; exit; }