R K
R K

Reputation: 327

Expected exception message not displaying in PHP

I want to write a program with database connectivity and exception handling in PHP. If I insert an incorrect username then it should display its corresponding error message, and if I insert the incorrect database it should display its corresponding error message.

But in the following program whether I insert incorrect database or incorrect username it only displays the message "Could not connect to database".

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

I am a beginner in PHP. Please comment below for any query.

EDIT

As asked by @Hatef Below is the var_dump of $conn when username is incorrect, password is correct and database name is correct

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

Below is the var_dump of $conn when the username is correct, password is correct and database name is incorrect.

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

Upvotes: 15

Views: 1755

Answers (6)

Paras Pitroda
Paras Pitroda

Reputation: 208

Using mysqli_connect, you will be able to pass database name within that same function so for connection purpose you don't need to wait for mysqli_select_db()

There are many error code which you will get after connection attempt and based on that you will be able to specify proper message.

I have updated your code and conditions so you will get idea

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

Hope it will help you.

Upvotes: 1

Chris Rocco
Chris Rocco

Reputation: 134

The MySQLi extension provides error information.

If $conn == false, call mysqli_connect_error() after to get your error message.

If you want to use your own message, mysqli_connect_errno() will return the error code, which you can use to handle it how you want.

From the PHP docs: 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);
?>

Upvotes: -1

TVA van Hesteren
TVA van Hesteren

Reputation: 1221

Make use of the PDO statements. The underneath example will tell you what error occurs when you use the try/catch setup.

Connect PDO with underneath code:

$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,
    ));

Then wrap your SQL in the try/catch setup like shown below:

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

Upvotes: 0

Bhupesh Shrestha
Bhupesh Shrestha

Reputation: 248

Try using the following for connection..

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

Upvotes: -1

rajatsaurastri
rajatsaurastri

Reputation: 653

As per your code, you sounds a good oops programmer. Well every programming language has its own set of rules & standards.

Lets go through your code

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

Here you are trying to initiate a connection. Then in your try catch block you are checking the connectivity.

Put you connection also in your try catch block & catch the exception.

For example :

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

Upvotes: 1

Agam Banga
Agam Banga

Reputation: 2693

By Default, mysql automatically throws the exception. To throw the exception manually, you need to write the below line at top of file This will throw exception even on mysqli_connect. So you need to add the connect method in try block. mysqli_report(MYSQLI_REPORT_STRICT);

UPDATE: In your case, don't write the above line, change the hostname & you will get the server error in your catch block.

Upvotes: 1

Related Questions