-1

I'm following a tutorial that teaches how to use PDO to connect to mySQL db via php and I'm trying to figure out if my connection is good. This is the code I have, but I can't tell how to check if I'm connected.

How can I update the following code so it returns a "connected" vs "no connected" message?

<?php    
class Database
{
    private static $dbName = 'benrud_carsData' ;
    private static $dbHost = 'localhost' ;
    private static $dbUsername = 'benrud_read5th';
    private static $dbUserPassword = 'XXXXXXX';

    private static $cont  = null;

    public function __construct() {
        die('Init function is not allowed');
    }

    public static function connect()
    {
       // One connection through whole application
       if ( null == self::$cont )
       {     
        try
        {
          self::$cont =  new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$dbUsername, self::$dbUserPassword); 
        }
        catch(PDOException $e)
        {
          die($e->getMessage()); 
        }
       }
       return self::$cont;
    }

    public static function disconnect()
    {
        self::$cont = null;
    }
}

?>
Mr. B
  • 2,677
  • 6
  • 32
  • 42
  • What would you want to return the message? It looks like `connect()` currently returns the connection. If you returned a message instead, it wouldn't return the connection any more, which is not good. – Don't Panic Oct 08 '18 at 21:47
  • You should look at the `Singlton` pattern, which you have about half way implemented. Better for DB is multiple Singlton pattern. It just so happens I have it on [GitHub](https://github.com/ArtisticPhoenix/Pattern) and Composer. – ArtisticPhoenix Oct 08 '18 at 21:49
  • @esqew The answers on that possible duplicate are interesting. In my experience, connection failure when constructing a new PDO will always throw a PDOException, whether PDO::ATTR_ERRMODE has been set or not. – Don't Panic Oct 08 '18 at 22:00

1 Answers1

0

If your connection fails, you'll get a PDOException, and that's currently being handled by dying with the exception message, so you'll definitely know it didn't work if that happens.

If you just need to see if it has established a connection yet, you can add a status method that checks if that static property is null. I showed it returning a boolean, so the calling code could determine what message to show, but you could return a message instead if you like.

public static function connectionStatus() {
    return !is_null(self::$cont);
}
Don't Panic
  • 41,125
  • 10
  • 61
  • 80