2017-05-03 38 views
15

我想用PHP編寫一個包含數據庫連接和異常處理的程序。如果我插入一個不正確的用戶名,那麼它應該顯示其相應的錯誤信息,如果我插入不正確的數據庫,它應該顯示其相應的錯誤信息。預期異常消息不在PHP中顯示

但在下列程序中,如果我插入了不正確的數據庫或不正確的用戶名,它只會顯示消息「無法連接到數據庫」。

<?php 
    $hostname = "localhost"; 
    $username = "root1"; 
    $password = ""; 
    $database = "php_thenewboston"; 
    $conn = mysqli_connect($hostname,$username,$password); 
    $conn_db = mysqli_select_db($conn,$database); 
    class ServerException extends Exception{} 
    class DatabaseException extends Exception{} 
    try{ 
     if(!$conn){ 
      throw new ServerException('Could not connect to server.'); 
     }elseif(!$conn_db){ 
      throw new DatabaseException('Could not connect to database.'); 
     }else{ 
      echo "Connected."; 
     } 
    }catch(ServerException $ex){ 
     echo "Error :".$ex->getMessage();   
    }catch(DatabaseException $ex){ 
     echo "Error :".$ex->getMessage(); 
    } 
?> 

我是PHP的初學者。 請在下面評論任何查詢。

編輯

由於要求通過@Hatef 下面是當用戶名不正確$connvar_dump,密碼正確和數據庫名稱是正確的

object(mysqli)#1 (19) { 
    ["affected_rows"]=> 
    int(-1) 
    ["client_info"]=> 
    string(79) "mysqlnd 5.0.12-dev - 20150407 - $Id: 241ae00989d1995ffcbbf63d579943635faf9972 $" 
    ["client_version"]=> 
    int(50012) 
    ["connect_errno"]=> 
    int(0) 
    ["connect_error"]=> 
    NULL 
    ["errno"]=> 
    int(1044) 
    ["error"]=> 
    string(68) "Access denied for user ''@'localhost' to database 'php_thenewboston'" 
    ["error_list"]=> 
    array(1) { 
    [0]=> 
    array(3) { 
     ["errno"]=> 
     int(1044) 
     ["sqlstate"]=> 
     string(5) "42000" 
     ["error"]=> 
     string(68) "Access denied for user ''@'localhost' to database 'php_thenewboston'" 
    } 
    } 
    ["field_count"]=> 
    int(0) 
    ["host_info"]=> 
    string(20) "localhost via TCP/IP" 
    ["info"]=> 
    NULL 
    ["insert_id"]=> 
    int(0) 
    ["server_info"]=> 
    string(21) "5.5.5-10.1.16-MariaDB" 
    ["server_version"]=> 
    int(50505) 
    ["stat"]=> 
    string(132) "Uptime: 1072 Threads: 1 Questions: 16 Slow queries: 0 Opens: 18 Flush tables: 1 Open tables: 11 Queries per second avg: 0.014" 
    ["sqlstate"]=> 
    string(5) "00000" 
    ["protocol_version"]=> 
    int(10) 
    ["thread_id"]=> 
    int(9) 
    ["warning_count"]=> 
    int(0) 
} 

下面是$conn時的var_dump用戶名正確,密碼正確,數據庫名稱不正確。

object(mysqli)#1 (19) { 
    ["affected_rows"]=> 
    int(-1) 
    ["client_info"]=> 
    string(79) "mysqlnd 5.0.12-dev - 20150407 - $Id: 241ae00989d1995ffcbbf63d579943635faf9972 $" 
    ["client_version"]=> 
    int(50012) 
    ["connect_errno"]=> 
    int(0) 
    ["connect_error"]=> 
    NULL 
    ["errno"]=> 
    int(1049) 
    ["error"]=> 
    string(36) "Unknown database 'php_thenewboston1'" 
    ["error_list"]=> 
    array(1) { 
    [0]=> 
    array(3) { 
     ["errno"]=> 
     int(1049) 
     ["sqlstate"]=> 
     string(5) "42000" 
     ["error"]=> 
     string(36) "Unknown database 'php_thenewboston1'" 
    } 
    } 
    ["field_count"]=> 
    int(0) 
    ["host_info"]=> 
    string(20) "localhost via TCP/IP" 
    ["info"]=> 
    NULL 
    ["insert_id"]=> 
    int(0) 
    ["server_info"]=> 
    string(21) "5.5.5-10.1.16-MariaDB" 
    ["server_version"]=> 
    int(50505) 
    ["stat"]=> 
    string(132) "Uptime: 1417 Threads: 1 Questions: 18 Slow queries: 0 Opens: 18 Flush tables: 1 Open tables: 11 Queries per second avg: 0.012" 
    ["sqlstate"]=> 
    string(5) "00000" 
    ["protocol_version"]=> 
    int(10) 
    ["thread_id"]=> 
    int(10) 
    ["warning_count"]=> 
    int(0) 
} 
+1

在你嘗試調用mysqli_select_db()和它的結果之前檢查'mysqli_select_db()'**的結果... –

+0

將你的mysqli_connect和mysqli_select_db放入你的try塊中,它會節省一些頭痛的。 – aynber

+2

我使用'error_reporting(E_ALL); ini_set('display_errors',1);'在頁面頂部,所以PHP會返回非常有用的消息。編輯:加'mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);'當處理DB – OldPadawan

回答

1

默認情況下,mysql自動拋出異常。要手動拋出異常,需要在文件頂部寫入下面的行 即使在mysqli_connect上,也會拋出異常。所以你需要在try塊中添加connect方法。 mysqli_report(MYSQLI_REPORT_STRICT);

更新:在你的情況下,不寫上面的線,更改主機名&你會得到服務器錯誤在你的catch塊。

+0

時,只需使用帶有「PDO :: ERRMODE_EXCEPTION」選項的try/catch設置我試過了,但不幸的是它給出了相同的消息。 –

+0

@RK嘗試更改主機名稱 –

+0

@RK是否適合您? –

1

根據你的代碼,你聽起來是一個很好的oops程序員。那麼每種編程語言都有自己的一套規則&標準。

讓我們去你的代碼

$conn = mysqli_connect($hostname,$username,$password); 
    $conn_db = mysqli_select_db($conn,$database); 
    class ServerException extends Exception{} 
    class DatabaseException extends Exception{} 

在這裏,你正試圖發起一個連接。然後在你的try catch塊中檢查連通性。

把你連接也放在你的try catch塊中&發現異常。

例如:

try 
{ 
    if ($db = mysqli_connect($hostname_db, $username_db, $password_db)) 
    { 
     //do something 
    } 
    else 
    { 
     throw new Exception('Unable to connect'); 
    } 
} 
catch(Exception $e) 
{ 
    echo $e->getMessage(); 
} 
-1

嘗試使用連接下面..

<?php 
$mysqli = new mysqli("localhost", "root", "", "php_thenewboston"); 


try{ 
     if(!$mysqli){ 
      throw new ServerException('Could not connect to server.'); 
     }else{ 
      echo "Connected."; 
     } 
    }catch(ServerException $ex){ 
     echo "Error :".$ex->getMessage();   
    }catch(DatabaseException $ex){ 
     echo "Error :".$ex->getMessage(); 
    } 
?> 
0

利用PDO語句。下面的例子會告訴你使用try/catch設置時發生了什麼錯誤。

連接PDO與下面的代碼:

$mysqli_pdo = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASS, array(
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', 
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, 
    )); 

然後包裹在try/catch語句設置你的SQL如下所示:

try { 
    //$mysqli_pdo->beginTransaction(); If you need transaction 
    $sql = $mysqli_pdo->prepare("[YOUR SQL]"); 
    $sql->bindValue(1, $INT_VAL, PDO::PARAM_INT); 
    $sql->bindValue(2, $STR_VAL, PDO::PARAM_STR); 
    $sql->execute(); 
    //$mysqli_pdo->commit(); Don't forget if you use transaction 
    } 
catch(Exception $e) { 
    echo $e->getMessage(); 
    //$mysqli_pdo->rollBack(); Don't forget if you use transaction 
    exit(); 
    } 
-1

MySQLi擴展提供了錯誤的信息。

如果是$conn == false,請撥打mysqli_connect_error()以獲取您的錯誤消息。

如果您想使用自己的消息,mysqli_connect_errno()將返回錯誤代碼,您可以使用它來處理它的方式。

從PHP文檔:http://php.net/manual/en/mysqli.errno.php

<?php 
$link = mysqli_connect("localhost", "my_user", "my_password", "world"); 

/* check connection */ 
if (mysqli_connect_errno()) { 
    printf("Connect failed: %s\n", mysqli_connect_error()); 
    exit(); 
} 

if (!mysqli_query($link, "SET a=1")) { 
    printf("Errorcode: %d\n", mysqli_errno($link)); 
} 

/* close connection */ 
mysqli_close($link); 
?> 
1

使用mysqli_connect,你將能夠同函數中傳遞的數據庫名稱,以便用於連接目的,你不需要等待mysqli_select_db()

有很多錯誤代碼,你會得到連接嘗試後,並基於你將能夠指定適當的消息。

我已經更新了你的代碼和條件,你會得到的想法

<?php 
     $hostname = "localhost"; 
     $username = "root1"; 
     $password = ""; 
     $database = "php_thenewboston"; 
     $conn = mysqli_connect($hostname,$username,$password,$database); 
     $error = mysqli_connect_errno(); 
     //$conn_db = mysqli_select_db($conn,$database); 
     class ServerException extends Exception{} 
     class DatabaseException extends Exception{} 
     try{ 
      if($error == 1044){ 
       throw new ServerException('Could not connect to server. Check Username'); 
      }elseif($error == 1045){ 
       throw new DatabaseException('Could not connect to server. Check Password'); 
      }elseif($error == 1049){ 
       throw new DatabaseException('Could not connect to database. Check Database Name'); 
      }else{ 
       echo "Connected."; 
      } 
     }catch(ServerException $ex){ 
      echo "Error :".$ex->getMessage();   
     }catch(DatabaseException $ex){ 
      echo "Error :".$ex->getMessage(); 
     } 
?> 

希望它會幫助你。