0

I have my db connection parameters set in a single file which I include on all pages I need it. Connection files looks like so... called connect.php :

$db_host        = '111.111.111.111';
$db_database    = 'test';
$db_user        = 'test';
$db_pass        = 'test';
$db_port        = '3306';

//db connection
try {
    $db = new PDO("mysql:host=$db_host;port=$db_port;dbname=$db_database;charset=utf8", $db_user, $db_pass, 
        array(
            PDO::ATTR_EMULATE_PREPARES => false, 
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, //PDO::ERRMODE_SILENT is default setting
            PDO::ATTR_PERSISTENT => false //when true 
            )
    );
}
catch(PDOException $e) {
    error_log("Failed to connect to database (/connect.php): ".$e->getMessage());
}

When I need to do things with the db I include this file and end up with something like this... called example.php :

require $_SERVER['DOCUMENT_ROOT'].'/assets/functions/connect.php';

$stmt = $db->prepare("
    SELECT 
        accounts.account_id,
    FROM accounts
    WHERE accounts.account_key = :account_key
");

//bindings
$binding = array(
    'account_key' => $_POST['account_key']
);
$stmt->execute($binding);   
//result (can only be one or none)
$result = $stmt->fetch(PDO::FETCH_ASSOC);

//if result
if($result)
{
    // result found so do something
}

Occasionally the database connection will fail (updating, I shut it down, its being hammered, whatever)... when that happens the PDOException I have in the try/catch works as it should and adds an entry into my error log saying so.

What I would also like to do is add a 'check' in my example.php so it doesn't attempt to do any database work if there is no connection (the include file with my connect script failed to get a connection). How would I go about this and what is the preferred method of doing so?

I'm not sure of the correct way to 'test' $db before my $stmt entry. Would there be a way to retry the connection if it was not set?

I realize I can leave it as it and there would be no problems, other than the database query fails and the code doesn't execute, but I want to have more options like adding another entry to the error log when this happens.

user756659
  • 3,372
  • 13
  • 55
  • 110
  • Well, do all these in the exception handling code. – Shadow Jul 21 '17 at 05:09
  • But you may also set a flag in the connection exception handling that indicates the db conbection is down. Most of the time xou would stop the procesding here entirely, there is no point in continuing the script if it will not work. – Shadow Jul 21 '17 at 05:16

1 Answers1

1

To stop further processings just add an exit() at the end of each catch block, unless you want to apply a finally block.

try {
    //...   
} catch(PDOException $e) {
    // Display a message and log the exception.
    exit();
}

Also, throwing exceptions and true/false/null validations must be applied through the whole connect/prepare/fetch/close operations involving data access. You may want to see a post of mine:

Your idea with including db connection file I find good, too. But think about using require_once, so that a db connection is created only once, not on any include.

Note: In my example I implemented a solution which - somehow - emulates the fact that all exceptions/errors should be handled only on the entry point of an application. So it's more directed toward the MVC concept, where all user requests are sent through a single file: index.php. In this file should almost all try-catch situations be handled (log and display). Inside other pages exceptions would then be thwrown and rethrown to the higher levels, until they reach the entry point, e.g index.php.

As for reconnecting to db, How it should be correlated with try-catch I don't know yet. But anyway it should imply a max-3-steps-iteration.

  • So by simply adding the `exit();` in my connect.php file that would stop everything AFTER the require call in example.php? – user756659 Jul 21 '17 at 06:25
  • I think the problem I am at is while the error log entry on connect.php is great... I will need to do error handling on example.php. By that I mean if there is no connection to do what I want on that specific page I need to do something else if you know what I mean. An example would be some php scripts that 'talk' with an app... if there is no response from the db and it can't do anything then I need to handle that back to the app somehow and let it know there was no db connection at that time. Hopefully that makes sense. – user756659 Jul 21 '17 at 06:33
  • @user756659 Yes. When an exception is thrown, then the program stops processing any other statements following the error-prone statement and jumps directly into the catch block. There you can handle the exception as you wish. But, if you don't implement the `exit()` function, the program will continue with the statements following the catch block, or with the statements found inside the finally` block, if one is defined. –  Jul 21 '17 at 07:30
  • @user756659 Yes, it make sense. Because `connect.php` is included in each file, then define a `$connectedToDb = FALSE` variable before your showed try-catch. If db connection is successful, then set it to `TRUE`. If not, then you land in the `catch`, where you log your event. But don't implement `exit` anymore. This way, the page statements are processed further as normal and they can read the value of `$connectedToDb`. If they see a `FALSE` value, then they know how to handle the situation. –  Jul 21 '17 at 07:30