/**
  * is the MySQL server connected?
  * @return boolean
  */
 function isConnected()
 {
     if (php_sapi_name() == 'fpm-fcgi') {
         return $this->mysqli != null;
     }
     //Web requests are short
     return $this->mysqli && @$this->mysqli->ping();
 }
Example #2
0
 /**
  * connect to the db and save the connection
  * @throws \Exception
  * @return bool|\mysqli
  */
 private function _getMysqli()
 {
     if (!$this->_mysqli instanceof \mysqli) {
         $this->_mysqli = @new \mysqli(static::DB_HOSTNAME, static::DB_USERNAME, static::DB_PASSWORD, static::DB_DATABASE, static::DB_PORT);
         if ($this->_mysqli->connect_error) {
             throw new \Exception("Error connecting to database: {$this->_mysqli->connect_error}");
         }
     } else {
         if (!$this->_mysqli->ping()) {
             $this->_mysqli = null;
             $this->_getMysqli();
         }
     }
     return $this->_mysqli;
 }
 /**
  * Prepares a sql query optionally as a prepared statement if the prepArgs
  * array is specified
  * @name query
  * @param str $sql SQL to execute
  * @param str $prepArgs Arguments for prepared statement queries
  * @since 0.1.0
  * @return object query results
  * <code>
  * <?php
  * $query = $db->query("select * from foo")
  *
  * //prepared (safe from injection)
  * $query = $db->query("select * from foo where foo_id = ?", ['i', 1]);
  *
  * ?>
  * </code>
  */
 public function query($sql, $prepArgs = false)
 {
     if (!$this->conn->ping()) {
         $this->conn->close();
         $this->connect();
     }
     try {
         if (is_array($prepArgs)) {
             $stmt = $this->conn->prepare($sql);
             if (false === $stmt) {
                 $this->error("Couldn't prepare statement: " . $this->conn->error);
             } else {
                 $method = new \ReflectionMethod('mysqli_stmt', 'bind_param');
                 $method->invokeArgs($stmt, $this->_mkrefs($prepArgs));
                 /* much love to jan kriedner */
                 $stmt->execute();
                 if ($stmt->insert_id > 0) {
                     $result = $stmt->insert_id;
                 } else {
                     $result = $stmt->get_result();
                 }
             }
         } else {
             $result = $this->conn->query($sql);
         }
     } catch (Exception $e) {
         $this->error($e->getMessage() . " SQL: {$sql}");
     }
     return $result;
 }
Example #4
0
 /**
  * Determines if the connection to the server is active.
  *
  * @return  boolean  True if connected to the database engine.
  *
  * @since   1.0
  */
 public function connected()
 {
     if (is_object($this->connection)) {
         return $this->connection->ping();
     }
     return false;
 }
 public function measurePing(&$micro)
 {
     $micro = -microtime(true);
     $result = $this->mysqli->ping();
     $micro += microtime(true);
     return $result;
 }
 public function ping()
 {
     if (!@$this->handler->ping()) {
         return $this->reconnect();
     }
     return true;
 }
Example #7
0
 /**
  * Ping a server connection or reconnect if there is no connection
  * @return bool
  */
 public function ping()
 {
     if (!$this->dbh) {
         return false;
     }
     return @$this->dbh->ping();
 }
Example #8
0
 public function reconnect()
 {
     if (!$this->mysqli->ping()) {
         $this->mysqli->close();
         return $this->connect();
     }
     return true;
 }
 public function testMysqliConnection()
 {
     $mysqliConn = new mysqli("localhost", "root", "eqBZKHCd775HA2fS", "JobGossip");
     $connection = $mysqliConn->ping();
     $this->assertTrue($connection);
     $mysqliConn->close();
     //cleanup test
 }
Example #10
0
 public static function setDatabase(mysqli $db)
 {
     self::$db = null;
     if ($db && $db->ping()) {
         self::$db = $db;
         return true;
     }
     return false;
 }
Example #11
0
File: MySQL.php Project: jasny/Q
 /**
  * Reconnect to the db server
  */
 public function reconnect()
 {
     if (isset($this->native) && @$this->native->ping()) {
         return;
     }
     $native = new mysqli($this->settings['host'], $this->settings['user'], $this->settings['password'], $this->settings['dbname'], $this->settings['port'], $this->settings['unix_socket']);
     if (!$native) {
         throw new DB_Exception("Connecting to mysql database failed: " . \mysqli::connect_error());
     }
     $this->native = $native;
 }
Example #12
0
 /**
  * Destructor: cierra la conexión a MySQL si está abierta
  * @throws DBException si no se puede cerrar la conexion
  */
 public function __destruct()
 {
     try {
         $pingResult = parent::ping();
     } catch (\Exception $e) {
         $pingResult = false;
     }
     if ($pingResult) {
         if (!parent::close()) {
             throw new DBException(mysqli_connect_error(), mysqli_connect_errno());
         }
     }
 }
Example #13
0
 /**
  * Is connected
  *
  * @return bool
  */
 public function isConnected()
 {
     if ($this->resource instanceof \mysqli) {
         // 检测连接是否有效
         if (!$this->resource->ping()) {
             $this->disconnect();
             return false;
         }
         return true;
     } else {
         return false;
     }
 }
Example #14
0
 /**
  * If there is no DB connection established yet, it connects and populates self::$connection attribute.
  *
  * Also "wakes up" connection if it has gone away.
  */
 protected function lazyConnect()
 {
     if (isset($this->connection)) {
         // Connection might have gone away.
         $this->connection->ping();
         return;
     }
     list($host, $user, $password, $database) = $this->config->getMulti(array('db_host', 'db_user', 'db_password', 'db_name'));
     $this->connection = new mysqli($host, $user, $password);
     if (mysqli_connect_errno()) {
         throw new PHPTracker_Persistence_Error('Unable to connect to mysql database: ' . mysqli_connect_error());
     }
     if (false === $this->connection->select_db($database)) {
         throw new PHPTracker_Persistence_Error("Unable to select database: {$database}.\n" . $this->connection->error);
     }
 }
Example #15
0
 public function probarConeccion()
 {
     $mysqli = new mysqli("104.236.75.102", "monty", "rioslopez", "itcVolBank");
     /* check connection */
     if ($mysqli->connect_errno) {
         printf("Connect failed: %s\n", $mysqli->connect_error);
         exit;
     }
     /* check if server is alive */
     if ($mysqli->ping()) {
         printf("Our connection is ok!\n");
     } else {
         printf("Error: %s\n", $mysqli->error);
     }
     /* close connection */
     $mysqli->close();
 }
Example #16
0
 /**
  * Запрос к базе данных
  *
  * @param Query|string $query Запрос
  * @throws \Exception
  * @return \mysqli_result
  */
 public function query($query)
 {
     if ($this->check_connection) {
         if (!parent::ping()) {
             $this->establish();
         }
     }
     if ($query instanceof query) {
         $this->query = $query->sql();
     } else {
         $this->query = $query;
     }
     $this->query_list[] = $this->query;
     $this->result = parent::query($this->query);
     if ($this->error) {
         throw new \Exception("MYSQL ERROR: {$this->error}.\nSQL: {$this->query}");
     }
     return $this->result;
 }
Example #17
0
	/**
	 * Destructor: cierra la conexión a MySQL si está abierta
	 * @throws DBException si no se puede cerrar la conexion
	 */
	public function __destruct() {
		if (parent::ping()) {
			if (!parent::close()) {
				throw new DBException(mysqli_connect_error(), mysqli_connect_errno());
			}
		}
	}
Example #18
0
 /**
  * Reconnect
  *
  * @return    void
  */
 public function reconnect()
 {
     if ($this->conn_id !== false && $this->conn_id->ping() === false) {
         $this->conn_id = false;
     }
 }
 /**
  * Checks if database is connected
  *
  * @return bool
  */
 public function isConnected()
 {
     // We think we're still connected
     if ($this->isConnected) {
         // Check if this is really the case or if the database server has gone away for some reason
         // Using mysqlnd ping() does not reconnect (which we would not want anyway since charset etc would not be reinitialized that way)
         $this->isConnected = $this->link->ping();
     }
     return $this->isConnected;
 }
Example #20
0
<?php

$mysqli = new mysqli("mysql-server", "root", "hogehoge", "sample");
$message = $mysqli->ping() ? 'Connect MySQL' : $mysqli->error;
echo $message;
Example #21
0
 /**
  * Checks if database is connected
  *
  * @return bool
  */
 public function isConnected()
 {
     // We think we're still connected
     if ($this->isConnected) {
         // Check if this is really the case or if the database server has gone away for some reason
         $this->isConnected = $this->link->ping();
     }
     return $this->isConnected;
 }
 public function isAvailable()
 {
     return $this->db->ping();
 }
Example #23
0
 public function Open()
 {
     if (!$this->connected) {
         try {
             parent::real_connect(!is_null($this->connect['server']) && (bool) $this->connect['persistent'] ? 'p:' . $this->connect['server'] : $this->connect['server'], $this->connect['username'], $this->connect['password'], $this->connect['database'], $this->connect['port']);
             // Make sure persistent connection is still alive
             if (!parent::ping()) {
                 throw new DatabaseException('Lost connection to database: unable to reconnect');
             }
             // Enable Unicode
             parent::set_charset('utf8');
             // Enable double quotes for quoting identifiers instead of backticks (parent::query() used to avoid Execute() overhead)
             parent::query("SET sql_mode='ANSI_QUOTES'");
             unset($this->connect['password']);
             $this->connected = true;
         } catch (WarningException $e) {
             if (mysqli_connect_errno()) {
                 throw new DatabaseException(mysqli_connect_error(), mysqli_connect_errno());
             } else {
                 throw $e;
             }
         }
     }
 }
Example #24
0
	public function runBatch(){
		// SEB: What is going on here? If numQueries is a count of the number of queries, why is it adding to itself? Why isn't it a function?
		$this->numQueries += count($this->queries);
		$out = array();
		// Ping the server and re-establish the connection if it has been dropped.
		parent::ping();
		
		// For each query...
		foreach($this->queries as $queryId => $query){
			// Run the query.
			$res = parent::query($query, MYSQLI_USE_RESULT);
			if($this->error) throw new exception($this->error, $this->errno); 

			// Append the results into a 3d array in $out.
			if(is_bool($res) == true) {
				$out[$queryId] = "";
			} else {
				while($row = $res->fetch_assoc()) $out[$queryId][] = $row;
			}
		}
		
		$this->queries = array();
		
		// Return the output to the caller.
		return $out;
	} 
Example #25
0
error_reporting(E_ERROR);
session_start();
$mysqlSettings[0]['hostname'] = "localhost";
$mysqlSettings[0]['username'] = "root";
$mysqlSettings[0]['password'] = "superman123";
$mysqlSettings[0]['database'] = "mc";
$mysqlSettings[1]['hostname'] = "localhost";
$mysqlSettings[1]['username'] = "root";
$mysqlSettings[1]['password'] = "";
$mysqlSettings[1]['database'] = "mc";
for ($connectionIndex = 0; $connectionIndex > -1; $connectionIndex++) {
    if (!$mysqlSettings[$connectionIndex]['hostname']) {
        die("No connection could be established to MySQL.");
    }
    $mysql = new mysqli($mysqlSettings[$connectionIndex]['hostname'], $mysqlSettings[$connectionIndex]['username'], $mysqlSettings[$connectionIndex]['password'], $mysqlSettings[$connectionIndex]['database']);
    if ($mysql->ping()) {
        break;
    }
}
function escape($item)
{
    if (get_magic_quotes_gpc()) {
        $item = stripcslashes($item);
    }
    return sanitizeText($item);
}
function sanitizeText($text)
{
    $text = str_replace("<", "&lt;", $text);
    $text = str_replace(">", "&gt;", $text);
    $text = str_replace("\"", "&quot;", $text);
Example #26
0
 public function onRun($currentTick)
 {
     $this->database->ping();
 }
function mysqltest()
{
    global $log_format, $db_con, $debug, $database, $mysql_host, $mysql_user, $mysql_password, $command_line, $tmp_dir;
    //  get our current MySQL thread id and if new, save it
    $thread_id = "" . $db_con->thread_id . "\r\n";
    $all_ids = @file_get_contents("" . $tmp_dir . "/thread_ids.txt");
    //  if the index procedure meanwhile was manually aborted (for multi threaded indexing)
    if (!is_file("" . $tmp_dir . "/thread_ids.txt") || !$all_ids) {
        $db_con->kill($thread_id);
        //close last MySQL connection
        $cl = '';
        $report = "Indexation manually aborted.";
        printCancel($report, $cl);
        printEndHTMLBody($cl);
        exit;
        //  terminate this indexing thread completely
    }
    $mysql_fail = '';
    $check1 = '0';
    $check2 = '0';
    if ($check1 = $db_con->ping() != '1') {
        $dbtries = 0;
        while ($dbtries < 5 && ($check1 = $db_con->ping() != '1')) {
            $dbtries++;
            printDB_errorReport('noSQL', $command_line, '1');
            sleep(10);
            $db_con = new mysqli($mysql_host, $mysql_user, $mysql_password);
            if (!$db_con) {
                $mysql_fail = '1';
            }
            //echo "<span class='blue sml'>&nbsp;&nbsp;Cannot connect to database.<br /></span>";
            if ($db_con) {
                $success = mysqli_select_db($link, $database);
                if (!$success) {
                    $mysql_fail = '1';
                    //echo "<p class='blue sml'>&nbsp;&nbsp;Cannot choose database.<br /></p>";
                }
            }
        }
        if ($check2 = $db_con->ping() != '1') {
            printDB_errorReport('noSucc', $command_line, '1');
            //  failed 5 times. End of index procedure
            printDB_errorReport('aborted', $command_line, '1');
            printDB_errorReport('end', $command_line, '1');
            die('');
        }
        printStandardReport('newSQL', $command_line, '1');
        //  reconnected to db
    }
    //  get our current MySQL thread id and if new, save it
    $thread_id = "" . $db_con->thread_id . "\r\n";
    $all_ids = @file("" . $tmp_dir . "/thread_ids.txt");
    //  if the index procedure meanwhile was manually aborted (for multi threaded indexing)
    if (!is_file("" . $tmp_dir . "/thread_ids.txt") || !is_array($all_ids)) {
        $db_con->kill($thread_id);
        //close last MySQL connection
        $cl = '';
        $report = "Indexation manually aborted.";
        printCancel($report, $cl);
        printEndHTMLBody($cl);
        exit;
        //  terminate this indexing thread completely
    }
    if (!in_array($thread_id, $all_ids)) {
        $fp = fopen("" . $tmp_dir . "/thread_ids.txt", "a+");
        //  try to write
        if (!is_writeable("" . $tmp_dir . "/thread_ids.txt")) {
            echo "\n                    <br /><br />\n                    <p class='warnadmin cntr'>\n                    <br /><br />\n                    Unable to open the file .../admin/" . $tmp_dir . "/thread_ids.txt\n                    <br /><br />\n                    Index procedure aborted.\n                    <br /><br /></p>\n                    <br /><br />\n                    <p class='evrow'><a class='bkbtn' href='admin.php' title='Go back to Admin'>Back to admin</a></p>\n                    <br /><br />\n                </body>\n            </html>\n                        ";
            exit;
        }
        if (!fwrite($fp, $thread_id)) {
            echo "\n                    <br /><br />\n                    <p class='warnadmin cntr'>\n                    <br /><br />\n                    Unable to write the actual MySQL thread-id into file " . $tmp_dir . "/thread_ids.txt\n                    <br /><br />\n                    Index procedure aborted.\n                    <br /><br /></p>\n                    <br /><br />\n                    <p class='evrow'><a class='bkbtn' href='admin.php' title='Go back to Admin'>Back to admin</a></p>\n                    <br /><br />\n                </body>\n            </html>\n                ";
            exit;
        }
        fclose($fp);
    }
    return $mysql_fail;
}
 /**
  * Method to call mysqli->ping() to keep unused connections open on
  * long-running scripts, or to reconnect timed out connections (if php.ini has
  * global mysqli.reconnect set to true). Can't do this directly using object
  * since _mysqli is protected.
  *
  * @return bool True if connection is up
  */
 public function ping()
 {
     return $this->_mysqli->ping();
 }
Example #29
0
 /**
  * Pings the server and re-connects when `mysqli.reconnect = 1`
  *
  * @return bool
  */
 public function ping()
 {
     return $this->_conn->ping();
 }
Example #30
0
 /**
  * {@inheritDoc}
  */
 protected function realPing()
 {
     return $this->link->ping();
 }