/** * Create a new connection to the database * * @param string $host The MySQL host * @param string $user The MySQL user * @param string $password The MySQL password for the user * @param string $dbName The MySQL database name * * @return Database A database object to interact with the database */ public function __construct($host, $user, $password, $dbName) { if (Service::getContainer()) { if ($logger = Service::getContainer()->get('monolog.logger.mysql')) { $this->logger = $logger; } } $this->dbc = new mysqli($host, $user, $password, $dbName); if ($this->dbc->connect_errno) { $this->logger->addAlert($this->dbc->connect_error); throw new Exception($this->dbc->connect_error, $this->dbc->connect_errno); } $this->dbc->set_charset("utf8"); }
public function connect($parameters, $selectDB = false) { // Normally $selectDB is set to false by the MySQLDatabase controller, as per convention $selectedDB = $selectDB && !empty($parameters['database']) ? $parameters['database'] : null; // Connection charset and collation $connCharset = Config::inst()->get('MySQLDatabase', 'connection_charset'); $connCollation = Config::inst()->get('MySQLDatabase', 'connection_collation'); if (!empty($parameters['port'])) { $this->dbConn = new MySQLi($parameters['server'], $parameters['username'], $parameters['password'], $selectedDB, $parameters['port']); } else { $this->dbConn = new MySQLi($parameters['server'], $parameters['username'], $parameters['password'], $selectedDB); } if ($this->dbConn->connect_error) { $this->databaseError("Couldn't connect to MySQL database | " . $this->dbConn->connect_error); } // Set charset and collation if given and not null. Can explicitly set to empty string to omit $charset = isset($parameters['charset']) ? $parameters['charset'] : $connCharset; if (!empty($charset)) { $this->dbConn->set_charset($charset); } $collation = isset($parameters['collation']) ? $parameters['collation'] : $connCollation; if (!empty($collation)) { $this->dbConn->query("SET collation_connection = {$collation}"); } }
public function __construct($hostname, $username, $password, $database) { $this->link = @new mysqli($hostname, $username, $password, $database); if (mysqli_connect_error()) { trigger_error('Error: Could not connect to database "' . $database . '"', E_USER_WARNING); die; } $this->link->set_charset('utf8'); $this->link->query("SET SQL_MODE = ''"); }
/** * 初始化数据库 * * @param array $config 数据库配置 */ protected static function _init_mysql($config = array()) { if ($config == NULL) { $config = $GLOBALS['config']['db']; } if (!self::$db) { self::$db = new mysqli($config['host'], $config['user'], $config['password'], $config['db_name']); if (0 == self::$db->connect_errno) { self::$db->set_charset('utf8'); } else { echo 'MySQL connect error' . PHP_EOL; } } }
/** * Constructor * * @param array $connectionData Connection Data parsed by parse_url() */ public function __construct(array $connectionData) { if (!self::isAvailable()) { error("MySQLi not installed - Update your PHP configuration"); } $port = isset($connectionData["port"]) ? (int) $connectionData["port"] : 3306; $pass = isset($connectionData["pass"]) ? $connectionData["pass"] : NULL; $db = trim($connectionData["path"], "/ "); $this->dbname = $db; $this->user = $connectionData["user"]; $this->password = $pass; $this->host = $connectionData["host"]; $this->port = $port; $this->mysqli = new MySQLi($this->host, $this->user, $this->password, $this->dbname, $this->port); $this->testError(); $this->mysqli->set_charset(str_replace("-", "", CHOQ::$encoding)); }
public function connect($parameters, $selectDB = false) { // Normally $selectDB is set to false by the MySQLDatabase controller, as per convention $selectedDB = $selectDB && !empty($parameters['database']) ? $parameters['database'] : null; if (!empty($parameters['port'])) { $this->dbConn = new MySQLi($parameters['server'], $parameters['username'], $parameters['password'], $selectedDB, $parameters['port']); } else { $this->dbConn = new MySQLi($parameters['server'], $parameters['username'], $parameters['password'], $selectedDB); } if ($this->dbConn->connect_error) { $this->databaseError("Couldn't connect to MySQL database | " . $this->dbConn->connect_error); } // Set charset if given and not null. Can explicitly set to empty string to omit $charset = isset($parameters['charset']) ? $parameters['charset'] : 'utf8'; if (!empty($charset)) { $this->dbConn->set_charset($charset); } }
function set_charset($charset) { if (parent::set_charset($charset)) { return true; } // the client library may not support utf8mb4 parent::set_charset('utf8'); return $this->query("SET NAMES {$charset}"); }
/** * Obtiene una instancia de un objeto de conexion a la base de datos * @param array $parametros * @return \mysqli Mysqli Instance * @throws string */ public static function getInstance(array $parametros = array()) { if (self::$instance) { return self::$instance; } $parametrosRequeridos = array("host", "user", "pass", "db"); \Validator::validateArrayKeys($parametrosRequeridos, $parametros); if (!array_key_exists("port", $parametros)) { $parametros["port"] = 3306; } elseif (empty($parametros["port"])) { $parametros["port"] = 3306; } $mysqli = new \MySQLi(\Validator::emptyString($parametros["host"]), \Validator::emptyString($parametros["user"]), $parametros["pass"], \Validator::emptyString($parametros["db"]), \Validator::int($parametros["port"])); if ($mysqli->connect_error) { $msg = "No se pudo conectar a la base de datos " . $mysqli->connect_errno . ':' . $mysqli->error; throw new Exception($msg); } $mysqli->set_charset("utf8"); self::$instance = $mysqli; return self::$instance; }
* @package Handy-q * @author JJuan <*****@*****.**> * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License * @link http://www.textblock.org */ require '../lang/spanish.lang.php'; $db_name = "handyq"; // The database we created earlier in phpMyAdmin. $db_server = "localhost"; // Change if you have this hosted. $db_user = "******"; // Your USERNAME $db_pass = ""; // Your PASSWORD. Working locally, mine is blank. Change if you plan on deploying. $mysqli = new MySQLi($db_server, $db_user, $db_pass, $db_name) or die(mysqli_error()); $mysqli->set_charset("utf8"); @($id = (int) $_GET['id']); $sql = mysqli_query($mysqli, "SELECT * FROM docmanager WHERE id = {$id} "); $data = mysqli_fetch_row($sql); // Aktionen $aktion = ''; if (isset($_GET['aktion'])) { $aktion = $_GET['aktion']; } if ($aktion == "") { echo 'Admin Area'; } if ($aktion == "print") { $sql = mysqli_query($mysqli, "SELECT * FROM docmanager ORDER BY fecha DESC"); echo '<table class="sortable">'; echo '<caption>' . DOCMANAGER_PRINT . '</caption>';
/** * Database connection * * @param bool $persistent * @return object */ public function db_connect($persistent = FALSE) { // Do we have a socket path? if ($this->hostname[0] === '/') { $hostname = NULL; $port = NULL; $socket = $this->hostname; } else { // Persistent connection support was added in PHP 5.3.0 $hostname = $persistent === TRUE && is_php('5.3') ? 'p:' . $this->hostname : $this->hostname; $port = empty($this->port) ? NULL : $this->port; $socket = NULL; } $client_flags = $this->compress === TRUE ? MYSQLI_CLIENT_COMPRESS : 0; $this->_mysqli = mysqli_init(); $this->_mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 10); if (isset($this->stricton)) { if ($this->stricton) { $this->_mysqli->options(MYSQLI_INIT_COMMAND, 'SET SESSION sql_mode = CONCAT(@@sql_mode, ",", "STRICT_ALL_TABLES")'); } else { $this->_mysqli->options(MYSQLI_INIT_COMMAND, 'SET SESSION sql_mode = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE( @@sql_mode, "STRICT_ALL_TABLES,", ""), ",STRICT_ALL_TABLES", ""), "STRICT_ALL_TABLES", ""), "STRICT_TRANS_TABLES,", ""), ",STRICT_TRANS_TABLES", ""), "STRICT_TRANS_TABLES", "")'); } } if (is_array($this->encrypt)) { $ssl = array(); empty($this->encrypt['ssl_key']) or $ssl['key'] = $this->encrypt['ssl_key']; empty($this->encrypt['ssl_cert']) or $ssl['cert'] = $this->encrypt['ssl_cert']; empty($this->encrypt['ssl_ca']) or $ssl['ca'] = $this->encrypt['ssl_ca']; empty($this->encrypt['ssl_capath']) or $ssl['capath'] = $this->encrypt['ssl_capath']; empty($this->encrypt['ssl_cipher']) or $ssl['cipher'] = $this->encrypt['ssl_cipher']; if (!empty($ssl)) { if (isset($this->encrypt['ssl_verify'])) { if ($this->encrypt['ssl_verify']) { defined('MYSQLI_OPT_SSL_VERIFY_SERVER_CERT') && $this->_mysqli->options(MYSQLI_OPT_SSL_VERIFY_SERVER_CERT, TRUE); } elseif (defined('MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT')) { $this->_mysqli->options(MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT, TRUE); } } $client_flags |= MYSQLI_CLIENT_SSL; $this->_mysqli->ssl_set(isset($ssl['key']) ? $ssl['key'] : NULL, isset($ssl['cert']) ? $ssl['cert'] : NULL, isset($ssl['ca']) ? $ssl['ca'] : NULL, isset($ssl['capath']) ? $ssl['capath'] : NULL, isset($ssl['cipher']) ? $ssl['cipher'] : NULL); } } if ($this->_mysqli->real_connect($hostname, $this->username, $this->password, $this->database, $port, $socket, $client_flags)) { // Prior to version 5.7.3, MySQL silently downgrades to an unencrypted connection if SSL setup fails if ($client_flags & MYSQLI_CLIENT_SSL && version_compare($this->_mysqli->client_info, '5.7.3', '<=') && empty($this->_mysqli->query("SHOW STATUS LIKE 'ssl_cipher'")->fetch_object()->Value)) { $this->_mysqli->close(); $message = 'MySQLi was configured for an SSL connection, but got an unencrypted connection instead!'; log_message('error', $message); return $this->db->db_debug ? $this->db->display_error($message, '', TRUE) : FALSE; } if (!$this->_mysqli->set_charset($this->char_set)) { log_message('error', "Database: Unable to set the configured connection charset ('{$this->char_set}')."); $this->_mysqli->close(); return $this->db->db_debug ? $this->display_error('db_unable_to_set_charset', $this->char_set) : FALSE; } return $this->_mysqli; } return FALSE; }
{ return mysql_fetch_array($consulta); } public function num_rows($consulta) { return mysql_num_rows($consulta); } public function getTotalConsultas() { return $this->total_consultas; } } $db_name = "handyq"; // The database we created earlier in phpMyAdmin. $db_server = "localhost"; // Change if you have this hosted. $db_user = "******"; // Your USERNAME $db_pass = ""; // Your PASSWORD. Working locally, mine is blank. Change if you plan on deploying. $mysqli = new MySQLi($db_server, $db_user, $db_pass, $db_name) or die(mysqli_error()); $mysqli->set_charset("iso 8859-1"); // Para editdeletedocs, de manera que pueda llamar a este archivo y no al suyo $mysql_hostname = "localhost"; $mysql_user = "******"; $mysql_password = ""; $mysql_database = "handyq"; $prefix = ""; $bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Opps some thing went wrong"); mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong"); mysql_query("SET NAMES 'iso 8859-1'");
$url = DEFAULT_URL . '/'; if (isset($_GET['slug'])) { $slug = $_GET['slug']; if ('@' == $slug) { $url = 'https://twitter.com/' . TWITTER_USERNAME; } else { if (' ' == $slug) { // + $url = 'https://plus.google.com/u/0/' . GOOGLE_PLUS_ID . '/posts'; } else { $slug = preg_replace('/[^a-z0-9]/si', '', $slug); if (is_numeric($slug) && strlen($slug) > 8) { $url = 'https://twitter.com/' . TWITTER_USERNAME . '/status/' . $slug; } else { $db = new MySQLi(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE); $db->set_charset('utf8mb4'); $escapedSlug = $db->real_escape_string($slug); $redirectResult = $db->query('SELECT url FROM redirect WHERE slug = "' . $escapedSlug . '"'); if ($redirectResult && $redirectResult->num_rows > 0) { $db->query('UPDATE redirect SET hits = hits + 1 WHERE slug = "' . $escapedSlug . '"'); $url = $redirectResult->fetch_object()->url; } else { $url = DEFAULT_URL . $_SERVER['REQUEST_URI']; } $db->close(); } } } } header('Location: ' . $url, null, 301); $attributeValue = htmlspecialchars($url);
/** * Connect to the database. * * @param bool $persistent * @return mixed */ public function connect($persistent = false) { // Do we have a socket path? if ($this->hostname[0] === '/') { $hostname = null; $port = null; $socket = $this->hostname; } else { $hostname = $persistent === true ? 'p:' . $this->hostname : $this->hostname; $port = empty($this->port) ? null : $this->port; $socket = null; } $client_flags = $this->compress === true ? MYSQLI_CLIENT_COMPRESS : 0; $this->mysqli = mysqli_init(); $this->mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 10); if (isset($this->strictOn)) { if ($this->strictOn) { $this->mysqli->options(MYSQLI_INIT_COMMAND, 'SET SESSION sql_mode = CONCAT(@@sql_mode, ",", "STRICT_ALL_TABLES")'); } else { $this->mysqli->options(MYSQLI_INIT_COMMAND, 'SET SESSION sql_mode = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE( @@sql_mode, "STRICT_ALL_TABLES,", ""), ",STRICT_ALL_TABLES", ""), "STRICT_ALL_TABLES", ""), "STRICT_TRANS_TABLES,", ""), ",STRICT_TRANS_TABLES", ""), "STRICT_TRANS_TABLES", "")'); } } if (is_array($this->encrypt)) { $ssl = []; empty($this->encrypt['ssl_key']) or $ssl['key'] = $this->encrypt['ssl_key']; empty($this->encrypt['ssl_cert']) or $ssl['cert'] = $this->encrypt['ssl_cert']; empty($this->encrypt['ssl_ca']) or $ssl['ca'] = $this->encrypt['ssl_ca']; empty($this->encrypt['ssl_capath']) or $ssl['capath'] = $this->encrypt['ssl_capath']; empty($this->encrypt['ssl_cipher']) or $ssl['cipher'] = $this->encrypt['ssl_cipher']; if (!empty($ssl)) { if (isset($this->encrypt['ssl_verify'])) { if ($this->encrypt['ssl_verify']) { defined('MYSQLI_OPT_SSL_VERIFY_SERVER_CERT') && $this->mysqli->options(MYSQLI_OPT_SSL_VERIFY_SERVER_CERT, true); } elseif (defined('MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT')) { $this->mysqli->options(MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT, true); } } $client_flags |= MYSQLI_CLIENT_SSL; $this->mysqli->ssl_set(isset($ssl['key']) ? $ssl['key'] : null, isset($ssl['cert']) ? $ssl['cert'] : null, isset($ssl['ca']) ? $ssl['ca'] : null, isset($ssl['capath']) ? $ssl['capath'] : null, isset($ssl['cipher']) ? $ssl['cipher'] : null); } } if ($this->mysqli->real_connect($hostname, $this->username, $this->password, $this->database, $port, $socket, $client_flags)) { // Prior to version 5.7.3, MySQL silently downgrades to an unencrypted connection if SSL setup fails if ($client_flags & MYSQLI_CLIENT_SSL && version_compare($this->mysqli->client_info, '5.7.3', '<=') && empty($this->mysqli->query("SHOW STATUS LIKE 'ssl_cipher'")->fetch_object()->Value)) { $this->mysqli->close(); $message = 'MySQLi was configured for an SSL connection, but got an unencrypted connection instead!'; log_message('error', $message); if ($this->db->db_debug) { throw new DatabaseException($message); } return false; } if (!$this->mysqli->set_charset($this->charset)) { log_message('error', "Database: Unable to set the configured connection charset ('{$this->charset}')."); $this->mysqli->close(); if ($this->db->debug) { throw new DatabaseException('Unable to set client connection character set: ' . $this->charset); } return false; } return $this->mysqli; } return false; }
<?php require 'config.php'; $url = DEFAULT_URL . '/'; if (isset($_GET['id'])) { $id = intval($_GET['id'], 36); if (!empty($id)) { $db = new MySQLi(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE); $db->set_charset('utf8'); $result = $db->query("SELECT url FROM redirect WHERE id = {$id}"); if ($result && $result->num_rows > 0) { $url = $result->fetch_object()->url; } $db->close(); } } header('Location: ' . $url, null, 302); exit;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Post a Message</title> </head> <body> <?php // This is an OOP version of the script from Chapter 13. if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Validate the data (omitted)! // Connect to the database: $mysqli = new MySQLi('localhost', 'root', '', 'forum'); $mysqli->set_charset('utf8'); // Make the query: $q = 'INSERT INTO messages (forum_id, parent_id, user_id, subject, body, date_entered) VALUES (?, ?, ?, ?, ?, NOW())'; // Prepare the statement: $stmt = $mysqli->prepare($q); // Bind the variables: $stmt->bind_param('iiiss', $forum_id, $parent_id, $user_id, $subject, $body); // Assign the values to variables: $forum_id = (int) $_POST['forum_id']; $parent_id = (int) $_POST['parent_id']; $user_id = 3; // The user_id value would normally come from the session. $subject = strip_tags($_POST['subject']); $body = strip_tags($_POST['body']); // Execute the query: $stmt->execute(); // Print a message based upon the result: if ($stmt->affected_rows == 1) {
/** * Skapa en databas-anslutning. * * Laddar inställningar från global $repo_root/db_settings/$db_alias.php. * $host, $user, $passwd och $dbname förväntas vara satta. * * @param string $db_alias namnet på anslutningen du vill skapa. (dvs db_settings/$db_alias.php). */ function __construct($db_alias, $debug = false) { global $repo_root, $notify; $this->do_debug = $debug; $settings_basefile = $repo_root . '/db_settings/' . $db_alias; $settings_file = $settings_basefile . '.php'; $settings_localfile = $settings_basefile . '.local.php'; require $settings_file; if (file_exists($settings_localfile)) { require $settings_localfile; } $this->db = $dbname; $this->host = $host; $this->port = isset($port) ? $port : 3306; $this->charset = $charset; $this->start_timer(); parent::__construct($host, $user, $passwd, $dbname, $this->port); $this->stop_timer(); if (mysqli_connect_errno()) { if ($this->do_debug) { $debuginfo = debug_backtrace(); $debuginfo = $debuginfo[0]; print "<p>MySQLi connection problem: " . mysqli_connect_errno() . " (" . mysqli_connect_error() . ").<br />" . "Problem encountered when trying to connect to " . $this->host . ":" . $this->port . ", database " . $this->db . ".<br />" . "The error was encountered in " . $debuginfo['file'] . ":" . $debuginfo['line'] . "<br /></p>"; debug_print_backtrace(); } else { $notify->admin_alert("Could not connect to SQL database: " . mysqli_connect_errno() . " (" . mysqli_connect_error() . ").", false); } die('<p>Kunde inte ansluta till databasen. Var god kontakta oss.</p>'); } $this->start_timer(); if (!parent::set_charset($charset)) { if ($this->do_debug) { $debuginfo = debug_backtrace(); $debuginfo = $debuginfo[0]; print "<p>MySQLi connection problem trying to set charset to \"{$charset}\": " . mysqli_errno() . " (" . mysqli_error() . ").<br />" . "The error was encountered in " . $debuginfo['file'] . ":" . $debuginfo['line'] . "<br /></p>"; debug_print_backtrace(); } else { $notify->admin_alert("Could not set charset for database connection: " . mysqli_errno() . " (" . mysqli_error() . ").", false); } die('<p>Ett problem uppstod med databasanslutningen. Var god kontakta oss.</p>'); } $this->stop_timer(); unset($user); unset($host); unset($passwd); unset($dbname); unset($charset); }
public function set_charset($charset = 'utf8') { return parent::set_charset($this->cfg['charset']) && parent::query("SET collation_connection = {$this->cfg['charset']}_bin"); }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Test Connect Database FindMyPet</title> </head> <body> <?php //Server local dùng để test web, chức năng /*$servername = "localhost"; $username = "******"; $password = ""; $dbname = "FindMyPet";*/ //Server internet dùng để nhập dữ liệu chung của nhóm $servername = "sql6.freemysqlhosting.net"; $username = "******"; $password = "******"; $dbname = "sql685411"; // Tao ket noi $conn = new MySQLi($servername, $username, $password, $dbname); $conn->set_charset('utf8'); if ($conn->connect_error) { echo "Ket noi that bai: " . $conn->connect_error; } echo "Ket noi thanh cong"; ?> </body> </html>