drjk87189 2017-07-21 04:38
浏览 51
已采纳

错误处理如果不存在pdo数据库连接?

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.

  • 写回答

1条回答 默认 最新

  • du9698 2017-07-21 05:27
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序