function mySqlUpit($upit, $tip) { $konekcija = mysqli_connect("localhost", "root", "", "0007cinevision"); $konekcija->set_charset("utf8"); if (mysqli_connect_errno()) { printf("Konekcija nije uspela: %s\n", mysqli_connect_error()); exit; } $rezultat = mysqli_query($konekcija, $upit); if (!$rezultat) { printf("Greska: %s\n", mysqli_error($konekcija)); exit; } if ($tip == 0) { return 0; } if ($tip == 1) { $rez = mysqli_fetch_array($rezultat, MYSQLI_NUM); $konekcija->close(); } else { if ($tip == 2) { $rez = array(); $i = 0; while (($red = mysqli_fetch_array($rezultat)) != NULL) { $rez[$i++] = $red; } } } if (!empty($rez)) { return $rez; } return -1; }
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 cometchatDBConnect() { global $dbh; $port = DB_PORT; if (empty($port)) { $port = '3306'; } $dbserver = explode(':', DB_SERVER); if (!empty($dbserver[1])) { $port = $dbserver[1]; } $db_server = $dbserver[0]; $dbh = mysqli_connect($db_server, DB_USERNAME, DB_PASSWORD, DB_NAME, $port); if (mysqli_connect_errno($dbh)) { $dbh = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME, $port, '/tmp/mysql5.sock'); } if (mysqli_connect_errno($dbh)) { echo "<h3>Unable to connect to database due to following error(s). Please check details in configuration file.</h3>"; if (!defined('DEV_MODE') || defined('DEV_MODE') && DEV_MODE != '1') { ini_set('display_errors', 'On'); echo mysqli_connect_error($dbh); ini_set('display_errors', 'Off'); } header('HTTP/1.1 503 Service Temporarily Unavailable'); header('Status: 503 Service Temporarily Unavailable'); header('Retry-After: 10'); /* 10 seconds */ exit; } mysqli_select_db($dbh, DB_NAME); mysqli_query($dbh, "SET NAMES utf8"); mysqli_query($dbh, "SET CHARACTER SET utf8"); mysqli_query($dbh, "SET COLLATION_CONNECTION = 'utf8_general_ci'"); }
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'); }
/** $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, $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; } return $link; } //else return FALSE; }
function getRank($a, $b, $c) { include 'config.php'; $con = mysqli_connect($IP, $user, $pass, $db); // echo "select `idCategory` from Placed where `idBid`=$c and `idAuction`=$a"; // echo "select `idCategory` from Placed where `idBid`=$c and `idAuction`=$a"; //echo "select `idCategory` from Placed where `idBid`=$c and `idAuction`=$a"; // $result=mysqli_query($con,"select `idCategory` from Placed where `idBid`=$c and `idAuction`=$a") or die(mysqli_error($con)); $result = mysqli_query($con, "select `idCategory` from Placed where `idBid`={$c} and `idAuction`={$a}") or die(mysqli_error($con)); // echo "select count(*)+1 as rank from Placed where `Price`>$b and `idAuction`=$a and `status` = 'A'"; // echo json_encode($result); // echo mysqli_num_rows($result); $row = mysqli_fetch_assoc($result); $c = $row['idCategory']; // echo $c.'sdf'; if (empty($c)) { return 0; } // echo "select count(*)+1 as rank from Placed where `Price`>$b and `idCategory`=$c and `idAuction`=$a and `status` = 'A'"; //echo "select count(*)+1 as rank from Placed where `Price`>$b and `idCategory`=$c and `idAuction`=$a and `status` = 'A'"; $result = mysqli_query($con, "select count(*)+1 as rank from Placed where `Price`>{$b} and `idCategory`={$c} and `idAuction`={$a} and `status` = 'A'") or die("Error" . mysqli_error($con)); $output = []; while ($row = mysqli_fetch_assoc($result)) { return $row['rank']; } }
public function conexion() { if (!isset($this->con)) { $this->con = mysqli_connect("localhost", "root", "", "inventiba") or die(mysqli_error()); //echo "Conexion exitosa"; } }
function insertDatabaseFunc($username, $password, $queryType, $entity) { require_once 'queryDatabaseHelper.php'; if (validUsernameAndPassword($username, $password)) { $link = mysqli_connect("localhost", "Tommy", "pickles", "Model"); if (strcmp($queryType, 'Unsubs') == 0) { $query = 'DELETE FROM `subscription` WHERE `username`=\'' . $username . '\' AND `orgnumber`=\'' . $entity . '\''; } elseif (strcmp($queryType, 'RSVP') == 0) { $query = 'INSERT IGNORE INTO `rsvp`(`username`, `eventnumber`) VALUES (\'' . $username . '\',' . $entity . ')'; } elseif (strcmp($queryType, 'Subs') == 0) { $query = 'INSERT INTO `subscription`(`username`, `orgnumber`) VALUES (\'' . $username . '\',\'' . $entity . '\')'; } elseif (strcmp($queryType, 'AndroidDevice') == 0) { $query = 'INSERT IGNORE INTO `androiddevice`(`username`, `device_id`) VALUES (\'' . $username . '\',\'' . $entity . '\')'; } if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit; } if (mysqli_query($link, $query)) { echo 'true'; } else { echo 'false'; } mysqli_close($link); } else { echo 'false'; } }
/** * Class constructor. Connects to Databaseserver and selects Database. * * @param string Servername * @param string Username * @param string Password * @param string Database */ public function __construct($server, $user, $password, $database = '') { // check for mysql extension if (!extension_loaded('mysqli')) { $this->showerror('You should install the PHP MySQLi extension!', false); } $this->server = $server; $this->user = $user; $this->password = $password; $this->database = $database; $this->link_id = @($GLOBALS['___mysqli_ston'] = mysqli_connect($this->server, $this->user, $this->password)); if (!$this->link_id) { //try to connect with no password an change it afterwards. only for root user if ($this->user == 'root') { $this->link_id = @($GLOBALS['___mysqli_ston'] = mysqli_connect($this->server, $this->user, '')); if ($this->link_id) { $this->query("SET PASSWORD = PASSWORD('" . $this->escape($this->password) . "')"); } else { $this->showerror('Establishing connection failed, exiting'); } } else { $this->showerror('Establishing connection failed, exiting'); } } if ($this->database != '') { if (!@(bool) mysqli_query($this->link_id, 'USE ' . $this->database)) { $this->showerror('Trying to use database ' . $this->database . ' failed, exiting'); } } }
public function setNewServer($host, $user, $password, $database, $faild = self::EXCEPTION_FAILD_MODE) { //$this->server=null; // if ($host == "" and $user == "" and $database == "") { throw new DatabaseArgumentsException(); } else { Database::$server = mysqli_connect($host, $user, $password, $database); // if (!Database::$server) { if ($faild == 2 && Config::get('panel.configured')) { throw new DatabaseConnectionException(); } else { if ($faild == 1) { \Errors::r_db(); } } } // mysqli_query(Database::$server, "SET NAMES " . Config::get("database.charset")); // Database::$serverData = ['host' => $host, "username" => $user, "password" => $password, "database" => $database]; // // return Database::$server; } }
public function open_connection() { $this->connection = mysqli_connect('localhost', 'root', '', 'projectbrowser'); if (mysqli_connect_errno()) { die("Database connection failed: " . mysqli_connect_error() . " (" . mysqli_connect_errno() . ")"); } }
function connect($db_type, $var1 = false, $var2 = false, $var3 = false, $var4 = false, $var5 = '') { global $db_connected, $pdo, $mysql_connect, $mysql_select_db, $db_type1, $db_prefix; $db_type1 = $db_type; $db_prefix = $var5; switch ($db_type) { case 'mysql': # var1 = db_host | var2 = db_user | var3 = db_pass | var4 = db_name | var5 = db_prefix try { $pdo = new PDO("mysql:host={$var1};dbname={$var4};charset=utf8", $var2, $var3); $db_connected = true; } catch (PDOException $e) { die("ERROR: 001"); } break; case 'sqlite': # var1 = db_path try { $pdo = new PDO("sqlite:{$var1}"); $db_connected = true; } catch (PDOException $e) { die("ERROR: 001"); } break; case 'mysqli': # var1 = db_host | var2 = db_user | var3 = db_pass | var4 = db_name | var5 = db_prefix $mysql_connect = mysqli_connect($var1, $var2, $var3, $var4) or die("ERROR: 001"); if ($mysql_connect) { mysqli_select_db($mysql_connect, $var4) or die("ERROR: 002"); mysqli_query($mysql_connect, "SET NAMES 'utf8'"); $db_connected = true; } break; } }
function __construct() { $this->connection = mysqli_connect($this->host, $this->user, $this->pass, $this->name); if (mysqli_connect_errno($this->connection)) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } }
/** * * @param string $db_server * @param string $db_user * @param string $db_password * @param bool|int $db_persist */ public function __construct($db_server, $db_user, $db_password, $db_persist) { $this->con = mysqli_connect(($db_persist == 1 ? 'p:' : '') . $db_server, $db_user, $db_password); if (mysqli_connect_error()) { die('Database error: ' . mysqli_connect_error()); } }
public function open_connection() { $this->connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_DBNAME); if (!$this->connection) { die("Database Connection Failed " . mysqli_error()); } }
public function __construct() { global $config; extract($config['database']); $this->connection = mysqli_connect($host, $username, $password) or die('MySQL Error: ' . mysql_error()); mysqli_select_db($this->connection, $database); }
/** * Crée la première connexion à un serveur MySQL via MySQLi * * @param string $host Chemin du serveur * @param int $port Port de connexion * @param string $login Nom d'utilisateur * @param string $pass Mot de passe * @param string $db Nom de la base * @param string $prefixe Préfixe des tables SPIP * @return array|bool * - false si la connexion a échoué * - tableau décrivant la connexion sinon */ function req_mysql_dist($host, $port, $login, $pass, $db = '', $prefixe = '') { if (!charger_php_extension('mysqli')) { return false; } if ($port) { $link = @mysqli_connect($host, $login, $pass, '', $port); } else { $link = @mysqli_connect($host, $login, $pass); } if (!$link) { spip_log('Echec mysqli_connect. Erreur : ' . mysqli_connect_error(), 'mysql.' . _LOG_HS); return false; } $last = ''; if (!$db) { $ok = $link; $db = 'spip'; } else { $ok = mysqli_select_db($link, $db); if (defined('_MYSQL_SET_SQL_MODE') or defined('_MYSQL_SQL_MODE_TEXT_NOT_NULL')) { mysqli_query($link, $last = "set sql_mode=''"); } } spip_log("Connexion MySQLi vers {$host}, base {$db}, prefixe {$prefixe} " . ($ok ? "operationnelle" : 'impossible'), _LOG_DEBUG); return !$ok ? false : array('db' => $db, 'last' => $last, 'prefixe' => $prefixe ? $prefixe : $db, 'link' => $link, 'total_requetes' => 0); }
function query($SQL, $select = false) { static $CONFIG = ['server' => 'localhost', 'username' => 'root', 'password' => 'root', 'database' => 'wt']; static $connection; if (!isset($connection)) { // Create connection $connection = mysqli_connect($CONFIG['server'], $CONFIG['username'], $CONFIG['password'], $CONFIG['database']); if (!$connection) { die('Could not connect to database!'); } } if ($select) { // IS A SELECT QUERY, RETURN ARRAY $results = mysqli_query($connection, $SQL); $toReturn = []; if (mysqli_num_rows($results) > 0) { while ($result = mysqli_fetch_assoc($results)) { array_push($toReturn, $result); } } return $toReturn; } else { // RETURN BOOL if (mysqli_query($connection, $SQL)) { return true; } else { return false; } } // Execute SQL }
function Populate() { //mysql connection $con = mysqli_connect("eu-cdbr-azure-west-a.cloudapp.net", "b8592f1b44ff9a", "fecb2128", "TeamProject"); if (mysqli_connect_errno()) { $result = "f"; } else { //query $query = "SELECT Name,Email FROM Subscriber"; $result = mysqli_query($con, $query); //initialize arrays $i = 0; $subnames = array(); $submails = array(); //loop through the database populating while ($sub = mysqli_fetch_assoc($result)) { $subnames[$i] = $sub['Name']; $submails[$i] = $sub['Email']; $i++; } //close conection and return mysqli_close($con); return array($subnames, $submails); } }
function validarLogin($login, $pass) { $con = mysqli_connect("*********", "**********", "**********", "************"); #Se comprueba la conexion if (mysqli_connect_errno()) { echo 'Error de conexion: ' . mysqli_connect_error(); exit; } #Se quitan posibles caracteres especiales [NUL (ASCII 0), \n, \r, \, ', ", y Control-Z] (sql injection) $login = mysqli_real_escape_string($con, $login); $pass = mysqli_real_escape_string($con, $pass); #Se comprueban login y pass hasheada $usuario = mysqli_query($con, "SELECT login, pwd FROM Usuario WHERE login = '******'"); #Se comprueba que se han devuelto resultados if (!$usuario) { echo 'Error en la consulta: ' . mysqli_error($con); exit; } #Se coge el resultado $result = mysqli_fetch_row($usuario); #Si coincide, se devuelve la lista de bichos de ese usuario if ($result[0] == $login && $result[1] == $pass) { return true; } else { return false; } }
public function open_connection() { $this->connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME); if (mysqli_connect_errno()) { die("Database connection failed: " . mysqli_connect_error() . "(" . mysqli_connect_errno() . ")"); } }
function Global_Init() { //session_start(); Load_Configs(); if (!strnatcasecmp(trim($GLOBALS['db']['type']), "LB")) { require_once 'inc/dbmodule_LB.php'; } if (!strnatcasecmp(trim($GLOBALS['db']['type']), "GD")) { require_once 'inc/dbmodule_GD.php'; } //echo "GLOBALS: <BR>"; print_r($GLOBALS['db']); echo "<BR>"; $source_db_ok = SQL_DB_OK("source"); if ($source_db_ok['error'] === false) { $GLOBALS['db']['s_resource'] = @mysql_connect($GLOBALS['db']['s_host'], $GLOBALS['db']['s_user'], $GLOBALS['db']['s_pass']) or die($_SERVER["SCRIPT_FILENAME"] . "Could not connect to Source MySQL Server. : " . mysql_error()); @mysql_selectdb($GLOBALS['db']['s_base']) or die("Could not connect to Source database [" . $GLOBALS['db']['s_base'] . "] : " . mysql_error()); $GLOBALS['db']['x_resource'] = @mysql_connect($GLOBALS['db']['x_host'], $GLOBALS['db']['x_user'], $GLOBALS['db']['x_pass']) or die($_SERVER["SCRIPT_FILENAME"] . "Could not connect to X-Ray MySQL Server. : " . mysql_error()); @mysql_selectdb($GLOBALS['db']['x_base']) or die("Could not connect to X-Ray database [" . $GLOBALS['db']['x_base'] . "] : " . mysql_error()); $GLOBALS['db']['s_link'] = mysqli_connect($GLOBALS['db']['s_host'], $GLOBALS['db']['s_user'], $GLOBALS['db']['s_pass'], $GLOBALS['db']['s_base']) or die($_SERVER["SCRIPT_FILENAME"] . "Could not connect to Source MySQL Server (multilink). : " . mysqli_error($GLOBALS['db']['s_link'])); mysqli_select_db($GLOBALS['db']['s_link'], $GLOBALS['db']['s_base']) or die("Could not connect to Source database (multilink) [" . $GLOBALS['db']['s_base'] . "] : " . mysqli_error($GLOBALS['db']['s_link'])); $GLOBALS['db']['x_link'] = mysqli_connect($GLOBALS['db']['x_host'], $GLOBALS['db']['x_user'], $GLOBALS['db']['x_pass'], $GLOBALS['db']['x_base']) or die($_SERVER["SCRIPT_FILENAME"] . "Could not connect to X-Ray MySQL Server (multilink). : " . mysqli_error($GLOBALS['db']['x_link'])); mysqli_select_db($GLOBALS['db']['x_link'], $GLOBALS['db']['x_base']) or die("Could not connect to X-Ray database (multilink) [" . $GLOBALS['db']['x_base'] . "] : " . mysqli_error($GLOBALS['db']['x_link'])); } else { $config_error .= $source_db_ok['message'] . "<BR>"; } // array_key_exists('form', $_POST) && $_POST['form']!="" ? $_GET = $_POST : NULL; // array_key_exists('force', $_GET) && $_GET['force']!="" ? $_POST = $_GET : NULL; if (count($_GET) > 0) { $_POST = $_GET; } // if($_POST['form']!=""){$_GET = $_POST;} // if($_GET['force']!=""){$_POST = $_GET;} if (!FixOutput_Bool($GLOBALS['config_settings']['settings']['first_setup'], true, false, true)) { $GLOBALS['worlds'] = Get_Worlds_Enabled(); } }
function getDatosAnteriores($nombreUsuario) { $datos = array(); if ($connect = mysqli_connect("localhost", "root", "", "prueba1")) { $sql_select = sprintf("select Nombre,Apellidos,Fecha_Nacimiento,DNI,Localidad,Provincia,CP,Telefono from datos_usuarios\r\n\t\t\t\t\t\t\tinner join credenciales on datos_usuarios.ID_Credenciales=credenciales.idCredenciales\r\n\t\t\t\t\t\t\twhere credenciales.Usuario= '%s';", $nombreUsuario); //echo $sql_select."</br>"; $resultado_queryDatos = mysqli_query($connect, $sql_select); if ($resultado_queryDatos == FALSE) { echo "Error al ejecutar la consulta:</br>"; echo mysqli_error($resultado_queryDatos) . "</br>"; } else { if (mysqli_num_rows($resultado_queryDatos) == 1) { $i = 0; $registro = mysqli_fetch_row($resultado_queryDatos); while ($i <= 7) { //echo $i." ".$registro[$i]."</br>"; $datos[$i] = $registro[$i]; $i++; } return $datos; } else { echo "El resultado es diferente uno"; return false; } } } else { echo "Error al conectar con BBDD </br>"; return false; } }
/** * Connect to server */ function sql_connect($sqlserver, $sqluser, $sqlpassword, $database, $port = false, $persistency = false, $new_link = false) { $this->persistency = $persistency; $this->user = $sqluser; $this->server = $sqlserver; $this->dbname = $database; $port = !$port ? NULL : $port; // Persistant connections not supported by the mysqli extension? $this->db_connect_id = @mysqli_connect($this->server, $this->user, $sqlpassword, $this->dbname, $port); if ($this->db_connect_id && $this->dbname != '') { @mysqli_query($this->db_connect_id, "SET NAMES 'utf8'"); // enforce strict mode on databases that support it if (version_compare($this->sql_server_info(true), '5.0.2', '>=')) { $result = @mysqli_query($this->db_connect_id, 'SELECT @@session.sql_mode AS sql_mode'); $row = @mysqli_fetch_assoc($result); @mysqli_free_result($result); $modes = array_map('trim', explode(',', $row['sql_mode'])); // TRADITIONAL includes STRICT_ALL_TABLES and STRICT_TRANS_TABLES if (!in_array('TRADITIONAL', $modes)) { if (!in_array('STRICT_ALL_TABLES', $modes)) { $modes[] = 'STRICT_ALL_TABLES'; } if (!in_array('STRICT_TRANS_TABLES', $modes)) { $modes[] = 'STRICT_TRANS_TABLES'; } } $mode = implode(',', $modes); @mysqli_query($this->db_connect_id, "SET SESSION sql_mode='{$mode}'"); } return $this->db_connect_id; } return $this->sql_error(''); }
function isInQueue() { // Reference Global Variables global $globalHostName; global $globalUserName; global $globalPassword; global $globalDatabase; // MySQL Connection $connection = mysqli_connect($globalHostName, $globalUserName, $globalPassword, $globalDatabase); // Connection Error Handling if ($connection->connect_error) { // Kill the Connection die("Could Not Connect to the Database"); } // MySQL Injection Neutralized Email Variable $safeEmail = mysqli_real_escape_string($connection, $_REQUEST['inputEmail']); // Query Preparation $query = mysqli_prepare($connection, 'SELECT COUNT(*) as total FROM users WHERE email = ?'); $query->bind_param('s', $safeEmail); // Query Execution mysqli_stmt_execute($query); // Query Result Analysis mysqli_stmt_bind_result($query, $total); $data = mysqli_stmt_fetch($query); //----- $connection->close(); // If That Email is Already Registered... if ($total > 0) { echo "true"; return true; } else { echo "false"; return false; } }
function connect() { $this->link = mysqli_connect($this->host, $this->name, $this->pass, $this->table) or die($this->error()); // $link=mysqli_connect($this->host,$this->name,$this->pass) or die ($this->error()); // mysqli_select_db($this->table,$link) or die("没该数据库:".$this->table); mysqli_query($this->link, "SET NAMES '{$this->ut}'"); }
public function connect() { if (!$this->con) { $this->currentCon = @mysqli_connect($this->db_host, $this->db_user, $this->db_pass); // mysql_connect() with variables defined at the start of Database class if ($this->currentCon) { $seldb = @mysqli_select_db($this->currentCon, $this->db_name); // Credentials have been pass through mysql_connect() now select the database if ($seldb) { $this->con = true; return true; // Connection has been made return TRUE } else { array_push($this->result, mysqli_error($this->currentCon)); return false; // Problem selecting database return FALSE } } else { array_push($this->result, mysqli_error($this->currentCon)); return false; // Problem connecting return FALSE } } else { return true; // Connection has already been made return TRUE } }
function display_product_details($id) { $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); $query3 = "SELECT * FROM food_items WHERE id= '{$id}' "; $result3 = mysqli_query($dbc, $query3); echo '<form action="fp-updateresult.php" method="post">'; echo '<table>'; echo '<tr>'; echo '<th>Name</th>'; echo '<th>Description</th>'; echo '<th>Price</th>'; echo '<th>Update</th>'; echo '</tr>'; while ($row3 = mysqli_fetch_array($result3)) { echo '<tr>'; echo '<td><input type="text" name="name" value="' . $row3['name'] . '" /></td>'; echo '<td><input type="text" name="description" value="' . $row3['description'] . '" /></td>'; echo '<td><input type="text" name="price" value="' . $row3['price'] . '" /></td>'; echo '<input type="hidden" name="proid" value="' . $row3['id'] . '" />'; echo '<td><input type="submit" name="submit" value="Update" style="margin:0" /></td>'; } echo '</tr>'; echo '</table>'; echo '</form>'; }
public static function _init_mysql($config = array()) { if (empty($config)) { // 记住不要把原来有的配置信息给强制换成$GLOBALS['config']['db'],否则换数据库会有问题 self::$config = empty(self::$config) ? $GLOBALS['config']['db'] : self::$config; } else { self::$config = $config; } if (!self::$conn) { self::$conn = @mysqli_connect(self::$config['host'], self::$config['user'], self::$config['pass'], self::$config['name'], self::$config['port']); if (mysqli_connect_errno()) { self::$conn_fail++; $errmsg = 'Mysql Connect failed[' . self::$conn_fail . ']: ' . mysqli_connect_error(); echo util::colorize(date("H:i:s") . " {$errmsg}\n\n", 'fail'); log::add($errmsg, "Error"); // 连接失败5次,中断进程 if (self::$conn_fail >= 5) { exit(250); } self::_init_mysql($config); } else { // 连接成功清零 self::$conn_fail = 0; self::$worker_pid = function_exists('posix_getpid') ? posix_getpid() : 0; mysqli_query(self::$conn, " SET character_set_connection=utf8, character_set_results=utf8, character_set_client=binary, sql_mode='' "); } } else { $curr_pid = function_exists('posix_getpid') ? posix_getpid() : 0; // 如果父进程已经生成资源就释放重新生成,因为多进程不能共享连接资源 if (self::$worker_pid != $curr_pid) { self::reset_connect(); } } }
function createNewPrediction() { define('DB_HOST', getenv('OPENSHIFT_MYSQL_DB_HOST')); define('DB_USER', getenv('OPENSHIFT_MYSQL_DB_USERNAME')); define('DB_PASS', getenv('OPENSHIFT_MYSQL_DB_PASSWORD')); define('DB_NAME', getenv('OPENSHIFT_GEAR_NAME')); $conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME) or die("Error: Couldn't connect" . DB_HOST . DB_USER . DB_PASS . DB_PORT . DB_NAME . mysqli_error($mysqlCon)); $response = array(); $bloodgroup = $_POST["Blood_group"]; $location = $_POST["Location"]; $available = $_POST["Available"]; $username = $_POST["name"]; $contact = $_POST["Contact_number"]; $nic = $_POST["Contact_number"]; $age = $_POST["Contact_number"]; $db = new DbConnect(); // mysql query $sql = "UPDATE Donor_details\n SET Blood_group={$bloodgroup},Location={$location},Available={$available},name={$username} WHERE Contact_number={$contact}"; $result = $conn->query($sql); if ($result) { $response["error"] = false; $response["message"] = "Prediction added successfully!"; } else { $response["error"] = true; $response["message"] = "Failed to add donor_details!"; } // echo json response echo json_encode($response); }