Reputation: 6812
I'm using XAMPP and I want to detect whether the MySQL database is running or not. My code looks like this:
$this->connection = mysqli_connect(
$this->host,
$this->name,
$this->pass,
$this->db
);
if ($this->connection->connect_errno)
{
$this->connection = false;
return false;
} else { $this->connection->set_charset('utf-8'); }
I receive the following log:
PHP Warning: mysqli_connect(): (HY000/2002): Connection refused ...
PHP Notice: Trying to get property of non-object in // This refers to $this->connection->connect_errno
PHP Fatal error: Call to a member function set_charset() on boolean
How can I prevent this? How can I check whether the database in general is available or not?
Upvotes: 1
Views: 804
Reputation: 158003
I am not the author of this answer, it's just the original version of the other post, which is the only correct solution for the conditions given
First you'll want to either disable warning reports or suppress them for mysqli_connect
call.
Then, instead of checking connect_errno
, first verify that connection
is a truthy value. Like so
$this->connection = @mysqli_connect( //<-- warnings suppressed
$this->host,
$this->name,
$this->pass,
$this->db
);
if (!$this->connection || $this->connection->connect_errno) //lazy evaluation will prevent any issues here
{
$this->connection = false;
return false;
} else { $this->connection->set_charset('utf-8'); }
Upvotes: 2
Reputation: 7573
First you'll want to either disable warning reports or suppress them for mysqli_connect
call, or embed it in a try/catch
block.
Then, instead of checking connect_errno
, instead first verify that connection
is a truthy value. Like so
$this->connection = false;
try {
$this->connection = mysqli_connect(
$this->host,
$this->name,
$this->pass,
$this->db
);
if (!$this->connection || $this->connection->connect_errno)
{
$this->connection = false;
return false;
} else {
$this->connection->set_charset('utf-8');
}
} catch ($e) { //something bad happened. Probably not recoverable.
$this->connection = false;
return false;
}
Upvotes: 3