Jump to content

MySQL mysqli Issue


random1

Recommended Posts

I'm working on some code that connects to MySQL using mysqli.

 

Its functioning well for when the MySQL service is running and responds but when the MySQL service is not running I'd like to redirect the page to an appropriate page.

 

Code:

 

// Check if PHP Extension 'mysqli' is installed and the selected method of database access (http://au2.php.net/mysqli)
if(extension_loaded('mysqli') && $method == 'mysqli')
{

// Set limitation of 5 seconds for attempt to connect to database
set_time_limit(5);

try
{
	// Create a connection using mysqli extension
	$this->m_Connection = new mysqli($dbhost, $dbusername, $dbpassword, $dbschema);

	//catch any errors
	if (mysqli_connect_errno() && $this->m_Connection->ping() == false)
	{
		// Failed to connect to database: log errors and redirect

		// Variables
		$errorMessage = '**** mysqli error ' . mysqli_connect_errno() . ' : ' . mysqli_connect_error();

		// Write to error log
		error_log($errorMessage);

		header('Location: ' . CONSTANT_REDIRECT_DATABASE_FAIL);
		return false;

		// Throw out gracefully
		throw new DatabaseCannotConnectException($errorMessage);
	}
	else
	{
		// Connected to MySQL with no errors
		// return true; // "<p><strong>Connected to MySQL Successfully</strong></p>";
		$this->m_Connection->select_db($dbschema);
		mysqli_set_charset($this->m_Connection, 'utf8');
	}
}
// Connection Failure
catch(Exception $e)
{
	error_log('**** Failed to connect to database : MySQL service not running');
	header('Location: ' . CONSTANT_REDIRECT_DATABASE_FAIL);
}
}

 

Problematic Line:

 

$this->m_Connection = new mysqli($dbhost, $dbusername, $dbpassword, $dbschema);

 

Errors shown:

Warning: mysqli::mysqli() [mysqli.mysqli0]: [2002] A connection attempt failed because the connected party did not (trying to connect via tcp://127.0.0.1:3306) in ...

Warning: mysqli::mysqli() [mysqli.mysqli0]: (HY000/2002): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. in ...

Fatal error: Maximum execution time of 5 seconds exceeded in ...

Link to comment
https://forums.phpfreaks.com/topic/206682-mysql-mysqli-issue/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.