function connect($server, $db, $user, $password, $socketPath, $charset = null, $port = false) { $connection = false; if ($socketPath !== false) { ini_set("mysqli.default_socket", $socketPath); } if ($this->UsePersistentConnection == true) { // Only supported on PHP 5.3 (mysqlnd) if (version_compare(PHP_VERSION, '5.3') > 0) { $this->Server = 'p:' . $this->Server; } else { eZDebug::writeWarning('mysqli only supports persistent connections when using php 5.3 and higher', 'eZMySQLiDB::connect'); } } eZPerfLogger::accumulatorStart('mysqli_connection', 'mysqli_total', 'Database connection'); $connection = mysqli_connect($server, $user, $password, null, (int) $port, $socketPath); $dbErrorText = mysqli_connect_error(); eZPerfLogger::accumulatorStop('mysqli_connection'); $maxAttempts = $this->connectRetryCount(); $waitTime = $this->connectRetryWaitTime(); $numAttempts = 1; while (!$connection && $numAttempts <= $maxAttempts) { sleep($waitTime); eZPerfLogger::accumulatorStart('mysqli_connection', 'mysqli_total', 'Database connection'); $connection = mysqli_connect($this->Server, $this->User, $this->Password, null, (int) $this->Port, $this->SocketPath); eZPerfLogger::accumulatorStop('mysqli_connection'); $numAttempts++; } $this->setError(); $this->IsConnected = true; if (!$connection) { eZDebug::writeError("Connection error: Couldn't connect to database. Please try again later or inform the system administrator.\n{$dbErrorText}", __CLASS__); $this->IsConnected = false; throw new eZDBNoConnectionException($server); } if ($this->IsConnected && $db != null) { eZPerfLogger::accumulatorStart('mysqli_connection', 'mysqli_total', 'Database connection'); $ret = mysqli_select_db($connection, $db); eZPerfLogger::accumulatorStop('mysqli_connection'); if (!$ret) { //$this->setError(); eZDebug::writeError("Connection error: " . mysqli_errno($connection) . ": " . mysqli_error($connection), "eZMySQLiDB"); $this->IsConnected = false; } } if ($charset !== null) { $originalCharset = $charset; $charset = eZCharsetInfo::realCharsetCode($charset); } if ($this->IsConnected and $charset !== null) { eZPerfLogger::accumulatorStart('mysqli_connection', 'mysqli_total', 'Database connection'); $status = mysqli_set_charset($connection, eZMySQLCharset::mapTo($charset)); eZPerfLogger::accumulatorStop('mysqli_connection'); if (!$status) { $this->setError(); eZDebug::writeWarning("Connection warning: " . mysqli_errno($connection) . ": " . mysqli_error($connection), "eZMySQLiDB"); } } return $connection; }
function dbConnect() { $conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD); mysqli_select_db($conn, DB_NAME); mysqli_set_charset($conn, 'utf8'); return $conn; }
public function __construct() { $this->db = new database(); $con = $this->db->connect("localhost", "root", "revive", "server"); mysqli_set_charset($con, "utf8"); $this->debugger = new debugger(); }
function cs_sql_connect($cs_db, $test = 0) { $error = ''; if (!extension_loaded('mysqli')) { $error = 'PHP extension mysqli must be activated!'; } else { $connect = mysqli_connect($cs_db['place'], $cs_db['user'], $cs_db['pwd'], $cs_db['name']) or $error = mysqli_connect_error(); } global $cs_main; $sql_charset = strtolower($cs_main['charset']); if (empty($error) and $sql_charset == 'utf-8') { # since php 5.0.5 - depends on mysql libs, too if (function_exists('mysqli_set_charset')) { mysqli_set_charset($connect, 'utf8'); } else { mysqli_query($connect, "SET NAMES 'utf8'") or $error = mysqli_error($connect); } } if (empty($test) and empty($error)) { return $connect; } elseif (empty($test)) { cs_error_sql(__FILE__, 'cs_sql_connect', $error, 1); } else { return $error; } }
function listarProductosSQL() { //Creamos la conexión con la función anterior $conexion = ConectarDB(); //generamos la consulta mysqli_set_charset($conexion, "utf8"); //formato de datos utf8 $sql = "SELECT *\tFROM producto"; if (!($result = mysqli_query($conexion, $sql))) { die; } //si la conexión falla cancelar programa $productos = array(); //creamos un array //guardamos en un array multidimensional todos los datos de la consulta $i = 0; while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) { $productos[$i] = $row; $i++; } desconectarDB($conexion); //desconectamos la base de datos return $productos; //devolvemos el array }
function abrirConex() { global $conexion; // Conexión con el servidor de base de datos MySQL $conexion = mysqli_connect('localhost', 'root', '', 'auditoria'); mysqli_set_charset($conexion, 'utf8'); }
function db_Connect($host = CMW_DB_HOST, $login = CMW_DB_LOGIN, $password = CMW_DB_PASSWORD, $name = CMW_DB_NAME, $port = _INI_MYSQLI_DEFAULT_PORT, $socket = _INI_MYSQLI_DEFAULT_SOCKET) { // Safely call this multiple times, only the first time has any effect // if (!db_IsConnected()) { global $db; $db = mysqli_init(); //mysqli_options($db, ...); if (defined('CMW_DB_PORT')) { $port = CMW_DB_PORT; } if (defined('CMW_DB_SOCKET')) { $socket = CMW_DB_SOCKET; } $flags = null; // Connect to the database // mysqli_real_connect($db, $host, $login, $password, $name, $port, $socket, $flags); // http://php.net/manual/en/mysqli.quickstart.connections.php if ($db->connect_errno) { db_Log("Failed to connect: (" . $db->connect_errno . ") " . $db->connect_error); } // Set character set to utf8mb4 mode (default is utf8mb3 (utf8). mb4 is required for Emoji) mysqli_set_charset($db, 'utf8mb4'); // More info: http://stackoverflow.com/questions/279170/utf-8-all-the-way-through } }
function db_connect() { global $link; $link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD) or die('Can not acces MySQL-server.'); mysqli_set_charset($link, 'utf8'); mysqli_select_db($link, DB_NAME) or die('Can not access database.'); }
function insertarTweetInfo($id_tweet, $tweet, $rts, $favs, $fecha_creacion, $usuario, $url_imagen, $followers, $followings, $num_tweets) { //Creamos la conexión a la base de datos $conexion = mysqli_connect("localhost", "root", "", "twitterdata"); //Comprobamos laconexión if ($conexion) { } else { die('Ha sucedido un error inexperador en la conexion de la base de datos<br>'); } //Codificación de la base de datos en utf8 mysqli_query($conexion, "SET NAMES 'utf8'"); mysqli_set_charset($conexion, "utf8"); //Creamos la sentencia SQL para insertar los datos de entrada $sql = "insert into tweets (id_tweet,tweet,rt,fav,fecha_creacion,usuario,url_imagen,followers,followings,num_tweets) \n values (" . $id_tweet . ",'" . $tweet . "'," . $rts . "," . $favs . ",'" . $fecha_creacion . "','" . $usuario . "','" . $url_imagen . "'," . $followers . "," . $followings . "," . $num_tweets . ");"; $consulta = mysqli_query($conexion, $sql); //Comprobamos si la consulta ha tenido éxito if ($consulta) { } else { die("No se ha podido insertar en la base de datos<br><br>" . mysqli_error($conexion)); } //Cerramos la conexión de la base de datos $close = mysqli_close($conexion); if ($close) { } else { die('Ha sucedido un error inexperado en la desconexion de la base de datos<br>'); } }
/** * constructor(string $dsn) * Connect to MySQL server. */ function __construct($dsn) { if (!is_callable("mysqli_connect")) { return $this->_setLastError("-1", "MySQLi extension is not loaded", "mysqli_connect"); } if (!empty($dsn["persist"])) { if (version_compare(PHP_VERSION, '5.3') < 0) { return $this->_setLastError("-1", "Persistent connections in MySQLi is allowable since PHP 5.3", "mysqli_connect"); } else { $dsn["host"] = "p:" . $dsn["host"]; } } if (isset($dsn['socket'])) { // Socket connection $this->link = mysqli_connect(null, empty($dsn['user']) ? 'root' : $dsn['user'], empty($dsn['pass']) ? '' : $dsn['pass'], preg_replace('{^/}s', '', $dsn['path']), null, $dsn['socket']); } else { if (isset($dsn['host'])) { // Host connection $this->link = mysqli_connect($dsn['host'], empty($dsn['user']) ? 'root' : $dsn['user'], empty($dsn['pass']) ? '' : $dsn['pass'], preg_replace('{^/}s', '', $dsn['path']), empty($dsn['port']) ? null : $dsn['port']); } else { return $this->_setDbError('mysqli_connect()'); } } $this->_resetLastError(); if (!$this->link) { return $this->_setDbError('mysqli_connect()'); } mysqli_set_charset($this->link, isset($dsn['enc']) ? $dsn['enc'] : 'UTF8'); }
/** * @inheritdocs */ function Open($connectionstring, $database, $username, $password, $charset = '', $bootstrap = '') { if (!function_exists("mysqli_connect")) { throw new DatabaseException('mysqli extension is not enabled on this server.', DatabaseException::$CONNECTION_ERROR); } // if the port is provided in the connection string then strip it out and provide it as a separate param $hostAndPort = explode(":", $connectionstring); $host = $hostAndPort[0]; $port = count($hostAndPort) > 1 ? $hostAndPort[1] : null; $connection = mysqli_connect($host, $username, $password, $database, $port); if (mysqli_connect_errno()) { throw new DatabaseException("Error connecting to database: " . mysqli_connect_error(), DatabaseException::$CONNECTION_ERROR); } if ($charset) { mysqli_set_charset($connection, $charset); if (mysqli_connect_errno()) { throw new DatabaseException("Unable to set charset: " . mysqli_connect_error(), DatabaseException::$CONNECTION_ERROR); } } if ($bootstrap) { $statements = explode(';', $bootstrap); foreach ($statements as $sql) { try { $this->Execute($connection, $sql); } catch (Exception $ex) { throw new DatabaseException("problem with bootstrap sql: " . $ex->getMessage(), DatabaseException::$ERROR_IN_QUERY); } } } return $connection; }
function ActualizarProductoSQL($productoAActualizar) { $codigo = $productoAActualizar["codigo"]; $detalle = $productoAActualizar["detalle"]; $precioVenta = $productoAActualizar["precio_venta"]; $precioCosto = $productoAActualizar["precio_costo"]; $iva = $productoAActualizar["iva"]; $stock = 0; $marca = $productoAActualizar["marca"]; $esMateriaPrima = true; //Creamos la conexión con la función anterior $conexion = ConectarDB(); //generamos la consulta mysqli_set_charset($conexion, "utf8"); //formato de datos utf8 $sql = " UPDATE producto\n SET detalle = '{$detalle}', precio_venta ='{$precioVenta}', precio_costo ='{$precioCosto}', iva ='{$iva}', stock = '{$stock}', marca='{$marca}', es_materia_prima='{$esMateriaPrima}'\n WHERE codigo = '{$codigo}';"; if (!($result = mysqli_query($conexion, $sql))) { die; } //si la conexión falla cancelar programa desconectarDB($conexion); //desconectamos la base de datos return true; // print_r($productos); //devolvemos el array }
/** $host - hostname:port, hostname:socket, socket, where a socket is to be provided, the : is compulsory, even if its first character, in which case localhost is assumed @param $cache_link - if TRUE, save reference to link for reuse. */ function db_connect($host, $user, $passwd, $dbname, $charset = NULL, $cache_link = TRUE) { global $_opendb_dblink; $index = strpos($host, ':'); if ($index !== FALSE) { $port = substr($host, $index + 1); $host = substr($host, 0, $index); // probably a socket if (!is_numeric($port)) { $socket = $port; unset($port); } } if (strlen($socket) > 0) { $link = @mysqli_connect($host, $user, $passwd, $dbname, NULL, $socket); } else { if (strlen($port) > 0) { $link = @mysqli_connect($host, $user, $passwd, $dbname, $port); } else { $link = @mysqli_connect($host, $user, $passwd, $dbname); } } if ($link !== FALSE) { if ($cache_link) { $_opendb_dblink = $link; } if ($charset != NULL) { @mysqli_set_charset($link, $charset); } return $link; } //else return FALSE; }
function dbConnect() { //Connect to database // Access global variables global $mysqli; global $dbHost; global $dbUser; global $dbPass; global $dbName; if (!isset($mysqli)) { // Attempt to connect to database server if (isset($dbPort)) { $mysqli = new mysqli($dbHost, $dbUser, $dbPass, $dbName, $dbPort); } else { $mysqli = new mysqli($dbHost, $dbUser, $dbPass, $dbName); } // If connection failed... if ($mysqli->connect_error) { webhooks_debug(" == Failed to connect to database: " . $mysqli->connect_error . " == ", true); } // if ($mysqli->connect_error) global $charset; mysqli_set_charset($mysqli, isset($charset) ? $charset : "utf8"); } // if(!isset($mysqli)) return $mysqli; }
function dbConnect() { ${"GLOBALS"}["ynvyvtgrlhv"] = "dbUser"; global $mysqli; global $dbHost; global $dbUser; global $dbPass; global $dbName; global $dbPort; ${"GLOBALS"}["cdbebx"] = "mysqli"; $luljlbwrlm = "charset"; $qcnjjmjhshu = "dbPass"; ${"GLOBALS"}["urqiwxbggy"] = "dbName"; ${"GLOBALS"}["glxpgvwccp"] = "dbHost"; if (isset(${${"GLOBALS"}["ptgzyszv"]})) { ${${"GLOBALS"}["mikmhj"]} = new mysqli(${${"GLOBALS"}["mxccww"]}, ${${"GLOBALS"}["ipgxwvjqcfs"]}, ${$qcnjjmjhshu}, ${${"GLOBALS"}["urqiwxbggy"]}, ${${"GLOBALS"}["ptgzyszv"]}); } else { ${${"GLOBALS"}["mikmhj"]} = new mysqli(${${"GLOBALS"}["glxpgvwccp"]}, ${${"GLOBALS"}["ynvyvtgrlhv"]}, ${${"GLOBALS"}["ukyvrmxs"]}, ${${"GLOBALS"}["thiajcew"]}); } if ($mysqli->connect_error) { fail("<!DOCTYPE html><html><head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\"/><link rel=\"Shortcut Icon\" type=\"image/ico\" href=\"/img/favicon.png\"><title>" . _("Can't connect to database") . "</title></head><style type=\"text/css\">body{background: #ffffff;font-family: Helvetica, Arial;}#wrapper{background: #f2f2f2;width: 300px;height: 130px;margin: -140px 0 0 -150px;position: absolute;top: 50%;left: 50%;-webkit-border-radius: 5px;-moz-border-radius: 5px;border-radius: 5px;}p{text-align: center;line-height: 18px;font-size: 12px;padding: 0 30px;}h2{font-weight: normal;text-align: center;font-size: 20px;}a{color: #000;}a:hover{text-decoration: none;}</style><body><div id=\"wrapper\"><p><h2>" . _("Can't connect to database") . "</h2></p><p>" . _("There is a problem connecting to the database. Please try again later or see this <a href=\"https://sendy.co/troubleshooting#cannot-connect-to-database\" target=\"_blank\">troubleshooting tip</a>.") . "</p></div></body></html>"); } global $charset; mysqli_set_charset(${${"GLOBALS"}["mikmhj"]}, isset(${${"GLOBALS"}["iwcsixdue"]}) ? ${$luljlbwrlm} : "utf8"); return ${${"GLOBALS"}["cdbebx"]}; }
function addMensajeProyecto($idProyecto, $mensaje) { $con = mysqli_connect(DBhost, DBuser, DBpassword, DATABASE); $json = array(); mysqli_set_charset($con, "UTF-8"); $mensaje = mysqli_real_escape_string($con, $mensaje); $result = mysqli_query($con, "select * from proyecto_alumno_profesor where IDProyecto={$idProyecto}"); $datos = mysqli_fetch_array($result); $idProfesor = $datos['IDProfesor']; $idAlumno = $datos['IDAlumno']; if (mysqli_query($con, "insert into observaciones values(default, '{$mensaje}', {$idProyecto}, {$idAlumno}, 1, now());")) { $json['warning'] = 0; } else { $json['warning'] = 1; } echo json_encode($json); $razon = "Nuevo mensaje de proyecto"; $body = "Se ha añadido un nuevo mensaje a tu proyecto, revísalo."; $proyecto = $idProyecto; $whoSend = 0; enviarEmail($razon, $body, $proyecto, $whoSend); $razon = "Nuevo mensaje de proyecto"; $body = "Se ha añadido un nuevo mensaje a tu proyecto, revísalo."; $proyecto = $idProyecto; $whoSend = 1; enviarEmail($razon, $body, $proyecto, $whoSend); }
function verTabla_DEM($codigo, $conexion) { $sql = "select documento.id as identificacion, documento.codigo as codigo, documento.num_docto as numero, \n documento.titulo as titulo, departamento.nombre as dpto\n from documento, departamento \n where substring(documento.codigo, 4, 3) = departamento.codigo \n and documento.codigo = 'PR-" . $codigo . "'\n order by departamento.nombre, documento.codigo, documento.num_docto;"; mysqli_set_charset($conexion, 'utf8'); $res = mysqli_query($conexion, $sql); return $res; }
function SliderSettings() { $count = array(); $link = mysqli_connect('127.0.0.1', 'solarstu_yan', 'zev1982z', 'solarstu_meow'); mysqli_set_charset($link, "utf8"); if (!$link) { echo mysqli_connect_error(); } if ($result = mysqli_query($link, "SELECT * FROM slider")) { echo '<form method="POST" action="' . $_SERVER['PHP_SELF'] . '" enctype="multipart/form-data"><table align="center">'; while ($row = mysqli_fetch_assoc($result)) { $index = $row['id']; // if (isset($_POST['delete' . $index])) { $this->delete($link, $row['id'], $row['url']); } // echo ' <tr> <td><img width="100%" height="75px" src="img/slider/' . $row['url'] . '"/></td> <td><button type="submit" class="btn_border" style="background:none;border:0px;" name="delete' . $row['id'] . '"><span class="glyphicon glyphicon-remove"></span></button> </td> </tr>'; } echo ' <tr> <td><input type="file" name="uploadfile"></td> <td><button class="btn_border" type="submit" style="background:none;border:0px;" name="upload"><span class="glyphicon glyphicon-plus"></span></button></td> </tr>'; echo '</form></table>'; } if (isset($_POST['upload'])) { $query = "INSERT INTO slider (url) VALUES ('" . $_FILES["uploadfile"]['name'] . "')"; $this->load($link, $query); } }
/** * 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; }
protected function getConnection() { if ($this->connection !== NULL) { if ($this->connectiontimelimit > 0 && $this->connectioncreatetime > 0 && time() - $this->connectioncreatetime > $this->connectiontimelimit) { $this->closeConnection(); } else { return $this->connection; } } $connstart = microtime(true); $att = 0; do { // hide errors. $this->connection = @mysqli_connect($this->dbhost, $this->dbuser, $this->dbpassword, $this->dbname); $att++; if (!$this->connection && $att < 4) { sleep(1); // try again in 1 sec } } while (!$this->connection && $att < 4); if ($this->connection === NULL) { throw new Exceptions\DBException('Can not connect to the DB server: ' . mysqli_connect_error(), '', 'connection', 1); } if ($this->connectioncharset != '') { mysqli_set_charset($this->connection, $this->connectioncharset); } $conntime = microtime(true) - $connstart; $this->profilerAction('dbconn', $conntime, "Database connection time {$conntime}"); $this->connectioncreatetime = time(); return $this->connection; }
function dbConnect() { //Connect to database //--------------------------------------------------------------// // Access global variables global $mysqli; global $dbHost; global $dbUser; global $dbPass; global $dbName; global $dbPort; // Attempt to connect to database server if (isset($dbPort)) { $mysqli = new mysqli($dbHost, $dbUser, $dbPass, $dbName, $dbPort); } else { $mysqli = new mysqli($dbHost, $dbUser, $dbPass, $dbName); } // If connection failed... if ($mysqli->connect_error) { fail("<!DOCTYPE html><html><head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\"/><link rel=\"Shortcut Icon\" type=\"image/ico\" href=\"/img/favicon.png\"><title>" . _('Can\'t connect to database') . "</title></head><style type=\"text/css\">body{background: #ffffff;font-family: Helvetica, Arial;}#wrapper{background: #f2f2f2;width: 300px;height: 110px;margin: -140px 0 0 -150px;position: absolute;top: 50%;left: 50%;-webkit-border-radius: 5px;-moz-border-radius: 5px;border-radius: 5px;}p{text-align: center;line-height: 18px;font-size: 12px;padding: 0 30px;}h2{font-weight: normal;text-align: center;font-size: 20px;}a{color: #000;}a:hover{text-decoration: none;}</style><body><div id=\"wrapper\"><p><h2>" . _('Can\'t connect to database') . "</h2></p><p>" . _('There is a problem connecting to the database. Please try again later.') . "</p></div></body></html>"); } global $charset; mysqli_set_charset($mysqli, isset($charset) ? $charset : "utf8"); return $mysqli; }
function db_init($host, $duser, $dpw, $dname) { $conn = mysqli_connect($host, $duser, $dpw); mysqli_set_charset($conn, 'utf8'); mysqli_select_db($conn, $dname); return $conn; }
function crearProductoSQL($productoACrear) { $codigo = $productoACrear["codigo"]; $detalle = $productoACrear["detalle"]; $precioVenta = $productoACrear["precio_venta"]; $precioCosto = $productoACrear["precio_costo"]; $iva = $productoACrear["iva"]; $stock = 0; $marca = $productoACrear["marca"]; $esMateriaPrima = true; //Creamos la conexión con la función anterior $conexion = ConectarDB(); //generamos la consulta mysqli_set_charset($conexion, "utf8"); //formato de datos utf8 $sql = " INSERT INTO producto (codigo, detalle, precio_venta, precio_costo, iva, stock, marca, es_materia_prima)\n VALUES ('{$codigo}','{$detalle}','{$precioVenta}','{$precioCosto}','{$iva}','{$stock}','{$marca}','{$esMateriaPrima}');"; if (!($result = mysqli_query($conexion, $sql))) { die; } //si la conexión falla cancelar programa desconectarDB($conexion); //desconectamos la base de datos return true; // print_r($productos); //devolvemos el array }
function SQLMultiquery($sql) { $mysqli = new mysqli('localhost', 'cp571579_ramil', ']2I.2qUs~tz}', 'cp571579_asmiiuri'); mysqli_set_charset($mysqli, "utf8"); /* проверка соединения */ if (mysqli_connect_errno()) { printf("Не удалось подключиться: %s\n", mysqli_connect_error()); exit; } $query = $sql; /* запускаем мультизапрос */ if ($mysqli->multi_query($query)) { do { /* получаем первый результирующий набор */ if ($result = $mysqli->store_result()) { while ($row = $result->fetch_row()) { //Отладка //printf("%s\n", $row[0]); } $result->free(); } /* печатаем разделитель */ if ($mysqli->more_results()) { //Отладка //printf("-----------------\n"); } } while ($mysqli->next_result()); } //var_dump($mysqli); $mysqli->close(); }
public function __construct($site = false, $blog = false) { //Get the user settings if (file_exists(realpath(realpath(__DIR__) . '/settings.php'))) { include_once realpath(realpath(__DIR__) . '/settings.php'); } else { if (file_exists(realpath(realpath(__DIR__) . '/../settings.php'))) { include_once realpath(realpath(__DIR__) . '/../settings.php'); } else { echo "Fancy has not been setup"; exit; } } $this->fancyVars = $fancyVars; $this->site = $site; $this->blog = $blog; $this->apiVersion = $fancyVars['apiVersion']; //Connect to the database. In the future I might create a system to allow for this to work with custom connections $this->con = new mysqli($this->fancyVars['dbaddr'], $this->fancyVars['dbuser'], $this->fancyVars['dbpass'], $this->fancyVars['dbname']); if ($this->con->connect_errno) { echo "<script>alert('Error connecting to Fancy database');</script>"; } mysqli_set_charset($this->con, "utf8mb4"); $this->init(); }
function getBlogPosts() { $db = new mysqli(db_host, db_uid, db_pwd, db_name); // open connection if ($db->connect_errno) { // are we connected properly? exit("Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error); } mysqli_set_charset($db, "utf8"); $sql = "SELECT * FROM posts ORDER BY end_date;"; $result = $db->query($sql); if (!$result) { // is there any error? exit("MySQL reports " . $db->error); } $posts = array(); while ($row = mysqli_fetch_assoc($result)) { $id = $row["id"]; $title = $row["title"]; $header_title = $row["header_title"]; $start_date = $row["start_date"]; $end_date = $row["end_date"]; $text = $row["text"]; $sidebar = $row["sidebar"]; array_push($posts, array($id, $title, $header_title, $start_date, $end_date, $text, $sidebar)); } $db->close(); // close connection echo json_encode($posts); }
function dbConnect() { //Connect to database //--------------------------------------------------------------// // Access global variables global $mysqli; global $dbHost; global $dbUser; global $dbPass; global $dbName; global $dbPort; // Attempt to connect to database server if (isset($dbPort)) { $mysqli = new mysqli($dbHost, $dbUser, $dbPass, $dbName, $dbPort); } else { $mysqli = new mysqli($dbHost, $dbUser, $dbPass, $dbName); } // If connection failed... if ($mysqli->connect_error) { fail(); } global $charset; mysqli_set_charset($mysqli, isset($charset) ? $charset : "utf8"); return $mysqli; }
/** * @param $connectionName * @return null */ function connection($connectionName) { static $configs; static $connections = []; if (null === $configs) { $configs = (include_once APP_DIR . '/config/databases.php'); } if (array_key_exists($connectionName, $connections)) { return $connections[$connectionName]; } else { if (array_key_exists($connectionName, $configs)) { $config = $configs[$connectionName]; $host = array_key_exists('host', $config) ? $config['host'] : ''; $port = array_key_exists('port', $config) ? $config['port'] : 3306; $user = array_key_exists('user', $config) ? $config['user'] : ''; $password = array_key_exists('password', $config) ? $config['password'] : ''; $db = array_key_exists('database', $config) ? $config['database'] : ''; $connections[$connectionName] = mysqli_connect('p:' . $host, $user, $password, $db, $port); mysqli_set_charset($connections[$connectionName], 'utf8'); return $connections[$connectionName]; } else { return null; } } }
function database_connect() { global $obj_db; // get calendar database if ($_SERVER["HTTP_HOST"] == 'localhost') { // local webserver on your computer, like XAMPP DEFINE('DBHOST', 'localhost'); DEFINE('DBUSER', 'root'); DEFINE('DBPASS', ''); DEFINE('DBNAAM', 'employee-work-schedule'); } else { // online use, so when you have the calendar on the online website DEFINE('DBHOST', 'localhost'); DEFINE('DBUSER', 'raman'); DEFINE('DBPASS', 'cPuXtGrNbnP5RTEJac'); DEFINE('DBNAAM', 'work_schedule'); } $obj_db = mysqli_connect(DBHOST, DBUSER, DBPASS, DBNAAM); if ($obj_db === FALSE) { $error = "Database connection failed"; printf("Connect failed: %s\n", mysqli_connect_error()); exit; } mysqli_set_charset($obj_db, 'utf8'); }
function DBConnect() { // Abre a conexão com o banco $link = @mysqli_connect(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE) or die(mysqli_connect_error()); mysqli_set_charset($link, DB_CHARSET) or die(mysqli_error($link)); return $link; }