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.

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

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效