dovhpmnm31216 2016-10-03 07:00
浏览 108
已采纳

PDO捕获PDOException错误

It works great if the connection is valid, but it seems PDOException doesn't actually work if the connection fails. The catch totally fails to execute. If its fails, it break execution of this line $this->dbh = new PDO("$db_driver:host=$db_host;dbname=$db_name", $db_user, $db_pass);. So i can't get PDOException in catch block. How do I keep get this to work?

<?php

namespace app\Helpers;

use \PDO;

/**
* Core class which exists only once through the application
*
*/
class Core
{
public $dbh; // handle of the db connexion
private static $instance;

// constructor to create a MySQLi instance (="MySQL Improved Extension")
private function __construct()
{

    $db_host = ConfigHelper::read('db.host');
    $db_name = ConfigHelper::read('db.basename');
    $db_user = ConfigHelper::read('db.user');
    $db_pass = ConfigHelper::read('db.password');
    $db_driver = ConfigHelper::read('db.driver');
    try {
        $this->dbh = new PDO("$db_driver:host=$db_host;dbname=$db_name", $db_user, $db_pass);
    } catch (PDOException $pdoex) {
        exit("Database connection failed: " . $pdoex->getMessage());
        return false;
    }

}
/**
 * get instance of Core object
 *
 * @return Object self
 */
public static function getInstance()
{
    if (!isset(self::$instance)) {
        $object = __CLASS__;
        self::$instance = new $object;
    }
    return self::$instance;
}

}
  • 写回答

1条回答 默认 最新

  • doudi1978 2016-10-03 07:17
    关注

    It is a namespace issue.

    When within a namespace, you have to address every root level class name by prepending it with a backslash.

    But you didn't.

    But the worst part is that you should not catch a PDOException at all. Just leave it alone and let it report to a site-wide report handler

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

报告相同问题?

悬赏问题

  • ¥15 MATLAB动图的问题
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名