2015-10-15 151 views
1

我正在使用XAMPP,我想檢測MySQL數據庫是否正在運行。我的代碼如下所示:如何檢測MySQL數據庫是否正在運行?

$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'); } 

我收到以下日誌:

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

我如何避免這種情況?我如何檢查一般數據庫是否可用?

+2

在'try/catch'語句中執行連接,以便您可以優雅地處理錯誤。 –

+0

CAn你展示全班? – Mihai

回答

3

首先,您需要禁用警告報告或將其屏蔽爲mysqli_connect調用,或將其嵌入到try/catch塊中。

然後,而不是檢查connect_errno,而是首先驗證connection是真值。像這樣

$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; 
} 
+6

千萬不要壓制警告,這是一個*不好的*計劃。 –

+0

我同意,我從來不是一個壓制警告的粉絲,所以我肯定願意接受建議,但是這個代碼應該足夠完善以處理任何問題。你會如何處理它? – CollinD

+3

我會把連接放在'try/catch'中,這樣錯誤就可以更好地處理了。 –

3

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

首先,你想要麼禁用警告報告或抑制它們mysqli_connect電話。

然後,而不是檢查connect_errno,首先驗證connection是真值。像這樣

$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'); } 
相關問題