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

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

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能