如何使用 MYSQLI_REPORT_STRICT 使 mysqli 抛出异常? [英] How to make mysqli throw exceptions using MYSQLI_REPORT_STRICT?

查看:30
本文介绍了如何使用 MYSQLI_REPORT_STRICT 使 mysqli 抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

mysqli 中有一个函数,叫做 mysqli_report(),它看起来像是 PDO 的 setAttribute() 方法的对应物,它的 ERRMODE_*> 常数.手册:

There is a function in mysqli, called mysqli_report(), which looks like a counterpart for PDO's setAttribute() method with its ERRMODE_* constants. The manual says:

MYSQLI_REPORT_STRICT 抛出 mysqli_sql_exception 错误而不是警告

因此,考虑到 PDO::ERRMODE_EXCEPTION,我尝试了此代码

So, having PDO::ERRMODE_EXCEPTION in mind, i tried this code

mysqli_report(MYSQLI_REPORT_STRICT);
$mysqli->query("foo");

但是,令我失望的是,它根本没有产生任何异常或警告.

but, to my disappointment, it produced no exception nor warning at all.

那么,问题来了:有没有办法让 mysqli 在不使用 MYSQLI_REPORT_ALL 的情况下抛出异常?

So, here goes the question: is there a way to tell mysqli to throw exceptions without using MYSQLI_REPORT_ALL?

推荐答案

经过一番研究,我终于了解到该函数的参数是一个位掩码,并且必须组合多个值才能获得所需的结果.最后的组合并不过分合乎逻辑,但它按预期工作,在忽略警告的同时抛出查询错误异常.

After some research I've finally learned that the function's parameter is a bitmask, and one have to combine several values to get the desired result. The final combination is not overly logical, but it works as intended, throwing an exception on a query error while ignoring warnings.

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

会产生想要的结果:

致命错误:未捕获的异常mysqli_sql_exception",消息为您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以获取在第 1 行的foo"附近使用的正确语法

Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'foo' at line 1'

这篇关于如何使用 MYSQLI_REPORT_STRICT 使 mysqli 抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆