0

I am trying to figure out how to handle the mysql connection within a class. Without always wrapping it in an if statement. Here is an example to help you understand what i am trying to do.

    class Database {
      protected $conn;
      protected $password;
      protected $username;
      protected $servername;

      public function Database(){
       $this->conn = new mysqli($this->servername,$this->username,$this->password);
      }

      public function scriptA(){
       if ($this->conn->connect_error) {
           die("Connection failed: " . $conn->connect_error);
        } else{
        //do script A
           return $result;
        }
     }

     public function scriptB(){
      if ($conn->connect_error) {
          die("Connection failed: " . $conn->connect_error);
      } else{
        //do script B
       return $result;
      }
    }

}

As you can see if i were to add more scripts i would have to add in a lot of if catches to check it has been connected. is there something like a function exception handler that php has? IE function foo throws exception?

user629283
  • 329
  • 1
  • 8
  • 23
  • You can write a class something like DB which will have connection in construct and call its function to do the query. In your scripts it would be something like `$db = new Database` and then `$db->Query('SELECT * FROM table');` – Autor69 Apr 27 '16 at 08:01
  • Use throw and catch for exception handling http://stackoverflow.com/questions/17549584/how-to-efficiently-use-try-catch-blocks-in-php – zubair Shaik Apr 27 '16 at 08:04
  • Try PDO: http://php.net/manual/en/book.pdo.php – Tobias Xy Apr 27 '16 at 08:20
  • @Autor69 Thats what i have done and I am just thinking if its best to make the class extends exception. – user629283 Apr 27 '16 at 08:26
  • @Hahn I would have to add a lot of try catch and throws in it. I am trying to keep the code simple and clean as i can. Without repeating the same thing. Sorry for being a pest about it. – user629283 Apr 27 '16 at 08:29
  • @TobiasXy I was actually looking into PDO and I've shelved a side for maybe another day lol. – user629283 Apr 27 '16 at 08:40
  • Why don't you use PDO ? – ismnoiet Apr 27 '16 at 08:43
  • @hamism I haven't used it before, but i can learn if that will stop me from repeating if and try catch statements in my code. – user629283 Apr 27 '16 at 08:51

2 Answers2

1

Here is a Simple way to handle exceptions using PDO:

    class Connection{
            public    $db;
            protected $DB_HOST;
            protected $DB_NAME;
            protected $DB_USER;
            protected $DB_PASSWORD;

            function __construct($db_host,$db_name,$db_user,$db_password){
                try{
                    $this->DB_HOST = $db_host;
                    $this->DB_NAME = $db_name;
                    $this->DB_USER = $db_user;
                    $this->DB_PASSWORD = $db_password;


                    $this->db = new pdo('mysql:host='.$this->DB_HOST.';dbname='.$this->DB_NAME,$this->DB_USER,$this->DB_PASSWORD);                      
                }catch(PDOException $e){
                    die($e->getMessage());
                }
            }   

    }

$con = new Connection('db_host','db_name','db_user','db_password');

// display something else here in case connection succeded.
echo 'congratulation you are no connected to your database !';
ismnoiet
  • 4,129
  • 24
  • 30
0
  1. It's a bad idea to use die() inside a class method. Your application might stop unexpectedly with partial output sent, errors not handled correctly etc. It's like you switch of electricity on the server while the script is running. The result is unpredictable. A small note here, you will have hard times testing the code with unit tests when you have die() statements. I can list more issues here if you will.

  2. PDO throws exceptions when something goes wrong. But most likely you do not need to catch the exception in Connection class because you can not handle the exception in this class. You can not sent error to the customer or log the error or rollback some activity in progress or notify administrator etc. You can not do anything except may be through a different exception.

  3. I think you need to review your application and catch PDOException in the code where you can really do something. Most likely this is done by your framework and you need to alter the framework's default behavior. Another option is to do this in the class which is responsible for some business logic. In this case you might do something different if SQL fails.

Community
  • 1
  • 1
Victor Smirnov
  • 3,450
  • 4
  • 30
  • 49