Zend_db update better error reporting

2019-07-16 18:51发布

问题:

When I update a record, I'm using the result from 'update' to determine if it worked correctly.

$a = $this->db->insert(self::TABLE, $saveData);

$a = 1 means that it updated one record. $a = 0 means that it didn't update anything. I can get a 0 if there was nothing changed in the form. But I also assume I can get a 0 if there was an error.

I'd like to be able to tell the user that the information was not updated because they didn't change anything or that there was an actual error of some sort.

Am I correct that an error returns 0 or does it return -1?

When ever I try to produce an error to check this, all I get is a Zend error that's not attractive and frankly rather un-useful.

回答1:

If the query failed due to a server error, or malformed query or invalid data, you will get an exception as opposed to a return value. So to do what you want, you can do something like this:

try {
    $a = $this->db->insert(self::TABLE, $saveData);

    if ($a == 0) {
        // return no data was updated
    } else {
        // return data was updated
    }
} catch(Zend_Exception $ex) {
    // query did NOT execute successfully
    // call $ex->getMessage() for the actual error
    // return failure result
}