Can I detect and handle MySQL Warnings with PHP?(我可以用 PHP 检测和处理 MySQL 警告吗?)
问题描述
我正在处理一个 MySQL 表,该表将 JobName 列定义为 UNIQUE.如果有人尝试使用数据库中已有的 JobName 将新 Job 保存到数据库中,MySQL 会抛出警告.
I'm dealing with a MySQL table that defines the JobName column as UNIQUE. If somebody tries to save a new Job to the database using a JobName that is already in the database, MySQL throws a warning.
我希望能够在我的 PHP 脚本中检测到这个警告,就像一个错误一样,并进行适当的处理.理想情况下,我想知道 MySQL 抛出了什么样的警告,以便我可以分支代码来处理它.
I would like to be able to detect this warning, just like an error, in my PHP script and deal with it appropriately. Ideally I would like to know what kind of warning MySQL has thrown so that I can branch the code to handle it.
这可能吗?如果没有,是因为MySQL没有这个能力,PHP没有这个能力,还是两者都有?
Is this possible? If not, is it because MySQL doesn't have this ability, PHP doesn't have this ability, or both?
推荐答案
对于本地标记"到 PHP 的警告需要更改 mysql/mysqli 驱动程序,这显然超出了本问题的范围.相反,您将不得不基本上检查您对数据库所做的每个查询是否有警告:
For warnings to be "flagged" to PHP natively would require changes to the mysql/mysqli driver, which is obviously beyond the scope of this question. Instead you're going to have to basically check every query you make on the database for warnings:
$warningCountResult = mysql_query("SELECT @@warning_count");
if ($warningCountResult) {
$warningCount = mysql_fetch_row($warningCountResult );
if ($warningCount[0] > 0) {
//Have warnings
$warningDetailResult = mysql_query("SHOW WARNINGS");
if ($warningDetailResult ) {
while ($warning = mysql_fetch_assoc($warningDetailResult) {
//Process it
}
}
}//Else no warnings
}
显然,使用整体应用会非常昂贵,因此您可能需要仔细考虑警告可能出现的时间和方式(这可能会导致您进行重构以消除它们).
Obviously this is going to be hideously expensive to apply en-mass, so you might need to carefully think about when and how warnings may arise (which may lead you to refactor to eliminate them).
作为参考,MySQL 显示警告
当然,您可以省去对 SELECT @@warning_count
的初始查询,这样可以为您每次执行节省一个查询,但我为了迂腐的完整性而包含它.
Of course, you could dispense with the initial query for the SELECT @@warning_count
, which would save you a query per execution, but I included it for pedantic completeness.
这篇关于我可以用 PHP 检测和处理 MySQL 警告吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我可以用 PHP 检测和处理 MySQL 警告吗?
基础教程推荐
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- PHP 守护进程/worker 环境 2022-01-01