Orbitall
Orbitall

Reputation: 661

catching a 'PDOException' when database is down

I am trying to catch an error if I cannot connect to database (eg xamp down or database connection down etc). I have tried to use PDO::errorCode() but yield no reuslts.

In my php I have a connection.php and a method ' to connect to the datatbase many times and return a new PDO instance to achieve various queries. The response displays the error message then all the php queries that call it, which also includes the name and password of the database in a non encrypted format.

CONNECTION.PHP

function connect()
{
    // set database server access variables:
    $host = "localhost";
    $user = "root";
    $pass = "password";
    $dbase = "dbName";

    //Establish a connection
    $db = new PDO("mysql:host=".$host."; dbname=".$dbase."", $user, $pass); //line 16
    $db -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);

    return $db;
}

RESPONSE

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it. ' in D:\Users\Username\Dropbox\Web\htdocs\sitename\php\data\connection.php:16 Stack trace: #0 D:\Users\Username\Dropbox\Web\htdocs\sitename\php\data\connection.php(16): PDO->__construct('mysql:host=loca...', 'root', 'password') #1 D:\Users\Username\Dropbox\Web\htdocs\sitename\php\function\active-user.php(28): connect() #2 D:\Users\Username\Dropbox\Web\htdocs\sitename\map-floorplan.php(10): include('D:\Users\Username...') #3 {main} thrown in D:\Users\Username\Dropbox\Web\htdocs\sitename\php\data\connection.php on line 16

Upvotes: 0

Views: 635

Answers (1)

PAlphen
PAlphen

Reputation: 186

do a try/catch to catch exceptions

try{
    $db = new PDO("mysql:host=".$host."; dbname=".$dbase."", $user, $pass); //line 16
    $db -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
    return $db;
} catch( PDOException $e){
    $originalError = $e->getMessage();
    echo 'something went wrong.. '.$originalError; 
    exit;
}

Upvotes: 1

Related Questions