Catch db2_prepare generated warning

2019-09-18 01:44发布

My DB2 class has a prepare function:

public function prepare()
{
    if (FALSE === ($this->stmt = db2_prepare($this->conn, $this->sql)))
    {
        throw new Exception($this->get_error());
    }

    return $this;
}

Some mysterious query is causing a warning in the php error log:

[26-Jan-2012 11:17:32] PHP Warning:  db2_prepare(): Statement Prepare Failed in /<path to file>/Db2.php on line 178

db2_prepare is not returning FALSE. Otherwise, an exception would be thrown, and I would get a backtrace.

Am I am not properly testing the db2_prepare's return value to catch legitimate errors/warnings, or does db2_prepare have a bug?

This is running on the Zend Server stack on i5/iseries/as400.

A workaround in this situation would be a try catch block that generates exceptions on warnings. Not sure how that would work, and that sounds like another post to me.

Also, @ is not an option here. It's generating a warning for a reason. I prefer not to stick my head in the sand.

Update: I finally tracked down the query. It was a badly formed insert statement. Even though the prepare failed and generated an error, a valid statement resource was returned and the script continued with generating an exception. I was using exec to call the script that contained the bad INSERT, but I did not return the output of the script which is why I never saw the error.

It still seems buggy to me, but I don't have time to pursue it further.

标签: php db2
1条回答
太酷不给撩
2楼-- · 2019-09-18 02:14

When checking the return, you probably want to compare the SQLSTATE instead of whether the preparation returned a successful resource.

You can retrieve the SQLSTATE in PHP using db2_stmt_error(), which will give you the SQL state of the last execution (if you pass a particular resource, the last execution on that resource). I believe the only SQLSTATE you want back from a PREPARE would be 00000, which is the code for a successful execution.

If you'd like to output a human-readable SQL Error Message, you can use db2_stmt_errormsg(), which will output the SQLSTATE and the corresponding error message string.

查看更多
登录 后发表回答