首页 > 解决方案 > 更详细的例外

问题描述

我几乎完成了将旧 sql 网站转换为 pdo 以移至 php7 并使用准备好的语句,但我遇到了一些错误。异常并不像我想的那么清楚,大多数错误都指向我的数据库类,例如

Uncaught Exception: 2020-01-18 20:23:35 - SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'username' AND UNIX_TIMESTAMP('2020-01-18 20:23:35')-UNIX_TIMESTAMP(date) < 30' at line 1 in file /home/test/public_html/backend/dbclass.php on line 39
Uncaught Exception: 2020-01-18 20:23:43 - SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '86.28.135.16'', donated=0, forumbanned='no', warned='no', modcomment='', enabled' at line 1 in file /home/test/public_html/backend/dbclass.php on line 39

我正在使用一个钝的单例类,这是最简单的方法(我知道这不是最好的),我有 1000 个查询,所以一个全局静态适合我让它更快。我不希望将每个查询都包装在 try/catch 中以识别异常。他们是否有任何可能有帮助的功能,比如回溯或 gettrace 我是新手,所以也许有更好的方法,任何帮助都将不胜感激

数据库类.php

<?php
define('DB_HOST', 'host');
define('DB_NAME', 'db');
define('DB_USER', 'user');
define('DB_PASS', 'pass');
define('DB_CHAR', 'utf8');

class DB
{
    protected static $instance = null;
    protected function __construct() {}
    protected function __clone() {}

    public static function instance()
    {
        if (self::$instance === null)
        {
            $opt  = array(
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES   => FALSE,
            );
            $dsn = 'mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset='.DB_CHAR;
            self::$instance = new PDO($dsn, DB_USER, DB_PASS, $opt);
        }
        return self::$instance;
    }

    public static function __callStatic($method, $args)
    {
        return call_user_func_array(array(self::instance(), $method), $args);
    }

    public static function run($sql, $args = [])
    {
        if (!$args)
        {
            return self::instance()->query($sql);
        }
        $stmt = self::instance()->prepare($sql);
        $stmt->execute($args);
        return $stmt;
    }
}

异常处理程序

function handleUncaughtException($e){
    // Show general page to public
    header("Location: exceptionerror.php"); 
    // Construct the error string
    $error = "Uncaught Exception: " . $message = date("Y-m-d H:i:s - ");
    $error .= $e->getMessage() . " in file " . $e->getFile() . " on line " . $e->getLine() . "\n";

    // Log details of error in a file
    error_log($error, 3, "error_log.txt");
}
// Register custom exception handler
set_exception_handler("handleUncaughtException");

查询示例

$stmt = DB::run("SELECT word FROM censor ORDER BY word");
while ($row = $stmt->fetch())

标签: phppdo

解决方案


推荐阅读