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

查看:124
本文介绍了我可以使用PHP检测和处理MySQL警告吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个将JobName列定义为UNIQUE的MySQL表。如果有人尝试使用已经在数据库中的JobName将新的作业保存到数据库,MySQL会发出警告。



我想能够检测到警告,就像一个错误,在我的PHP脚本,并适当地处理它。理想情况下,我想知道MySQL抛出什么样的警告,以便我可以分配代码来处理它。



这可能吗?如果没有,那是因为MySQL没有这种能力,PHP没有这种能力,还是两者兼有?

解决方案

对于本来对PHP进行标记的警告,需要更改mysql / mysqli驱动程序,这显然超出了这个问题的范围。相反,您将必须基本检查您在数据库中发现的每个查询,以获取警告:

  $ warningCountResult = mysql_query( SELECT @@ warning_count); 
if($ warningCountResult){
$ warningCount = mysql_fetch_row($ warningCountResult);
if($ warningCount [0]> 0){
//有警告
$ warningDetailResult = mysql_query(SHOW WARNINGS);
if($ warningDetailResult){
while($ warning = mysql_fetch_assoc(warningDetailResult){
//处理
}
}
} // Else没有警告
}

显然,应用en-mass是非常昂贵的,所以您可能需要仔细考虑可能发生的警告的时间和方式(可能会导致重构消除它们)。



为了参考, MySQL SHOW WARNINGS



当然,您可以省略对 SELECT @@ warning_count 的初始查询,这样可以为每个执行节省一个查询,但是我将其包括在内。 / p>

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.

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.

Is this possible? If not, is it because MySQL doesn't have this ability, PHP doesn't have this ability, or both?

解决方案

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).

For reference, MySQL SHOW WARNINGS

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天全站免登陆