php - 对所有PDO查询进行一次全局尝试{}捕获{}

标签 php mysql pdo error-handling try-catch

我很少在失败时对数据库查询使用唯一的错误消息

我经常使用简短的标准消息,例如“数据库错误/失败。请与网站管理员联系”或类似的消息。或自动发送给我

我正在寻找一种在PDO中全局设置一次try {}和catch {}的方法。所以我不必一遍又一遍地写

那可能吗?也许把它包装成一小堂课?

最佳答案

在良好的设计应用程序中,您将使用设计模式进行编写。例如,您可以使用MVC方法实现此目的:

模型

class Students {

    private pdo;

    function __construct($pdo){
    //do something
    $this->pdo = $pdo;
    }

    function get_all_students(){
        $stmt = $this->pdo->prepare("SELECT * FROM Students");
        $stmt->execute();
        $result = $stmt->fetchAll();

        return $result;
    }

}

Controller
class StudentsController{

    function GetStudentAction(){
        //here you create an instance of that model
        $students_model = new Students();
        $students = $students_model->get_all_students();
        return $students;
    }

}

用法
<?php
include 'Students.php';
include 'StudentsController.php';

try {
     $students = new StudentController();
     $all_students = $students->GetStudentAction();

    //then you have more other models 
    //for example:
     $professors = new ProfessorsController();
     $math_professors = $professors->GetMathProfessorsAction();
}
catch( PDOException $Exception ) {
    //do something with the Exception
    echo( $Exception->getMessage( ) , $Exception->getCode( ) );
}

?>

关于php - 对所有PDO查询进行一次全局尝试{}捕获{},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24687458/

相关文章:

php - 填充连接表

MySQL 双重排序

php - 查询数据到json响应

php - PDO 不适用于 SSL

php - 如何在 php-ml 上使用朴素贝叶斯将新样本添加到同一标签?

php - PHP 的 "Virtual Directory Support"是我认为的吗?

PHP/MySQL - 递增变量名以循环获取数据

php - 调用多个存储过程时出现MySQL PDO general error 2014

php - 如何将此 SQL 查询转换为 Laravel Eloquent 或查询生成器

php - 有哪些有用的 PHP 习语?