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

错误处理如果不存在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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里