php - 更详细的例外
问题描述
我几乎完成了将旧 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())
解决方案
推荐阅读
- python - 如何在 discord.py 的 discord.ext.tasks 循环中使用上下文?
- javascript - 每次点击都无法选中 mat-checkbox
- mysql - SQL 查询与 2 个表的连接,并在第二个表中创建具有多个外键的新列集
- ruby-on-rails - ActionMailer 添加 cc 和 bcc 作为选项
- javascript - 我们可以从 javascript 中的单个对象键值中获取对象吗?
- mysql - 在MySQL之间/结束时用“x”或“$”替换数值
- c# - 是否可以使用函数大括号自动完成?c# 视觉工作室
- http - 如何正确编码 UTF-8 中的 HTTP 响应字节?
- r - 从两个独立的数据库中根据多个条件选择行
- java - 在启动消费者应用程序时自动调用应用程序(在消费者项目中添加为不可执行的jar)方法