PHP

时间:2017-05-03 17:57:22

标签: php mysql

我想在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所说 当用户名不正确,密码正确且数据库名称正确时,下面是var_dump的{​​{1}}

$conn

当用户名正确,密码正确且数据库名称不正确时,下面是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) } 的var_dump。

$conn

6 个答案:

答案 0 :(得分:1)

默认情况下,mysql会自动抛出异常。要手动抛出异常,您需要在文件顶部写下面的行 即使在mysqli_connect上也会抛出异常。所以你需要在try块中添加connect方法。 mysqli_report(MYSQLI_REPORT_STRICT);

更新:在你的情况下,不要写上面的行,更改主机名和&amp;您将在catch块中收到服务器错误。

答案 1 :(得分: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 block&amp; amp;抓住例外。

例如:

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();
}

答案 2 :(得分: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();
       }
?>

希望它会对你有所帮助。

答案 3 :(得分: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,
    ));

然后将您的SQL包装在try / catch设置中,如下所示:

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();
    }

答案 4 :(得分:-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();
   }
?>

答案 5 :(得分:-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);
?>
相关问题