我可以用 PHP 检测和处理 MySQL 警告吗? [英] Can I detect and handle MySQL Warnings with PHP?

查看:38
本文介绍了我可以用 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 警告吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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