3

Zend_Db_Adapter::update()返回受更新操作影响的行数。确定查询是否成功的最佳方法是什么?

$data = array(
    'updated_on'      => '2007-03-23',
    'bug_status'      => 'FIXED'
); 

$n = $db->update('bugs', $data, 'bug_id = 2');
4

3 回答 3

5
$data = array(
    'updated_on' => '2007-03-23',
    'bug_status' => 'FIXED',
);
$n = 0;
try {
    $n = $db->update('bugs', $data, 'bug_id = 2');
} catch (Zend_Exception $e) {
    die('Something went wrong: ' . $e->getMessage());
}
if (empty($n)) {
    die('Zero rows affected');
}
于 2012-07-15T21:33:20.527 回答
3

如果您只是在寻找布尔返回值,则此解决方案是处理模型中成功的最佳解决方案:

类 Default_Model_Test 扩展 Zend_Db_Table {

public function updateTest($testId, $testData){

    try {

        $this->_db->update('test', $testData, array(
            'id = ?'        => $testId
        ));

        return true;

    }
    catch (Exception $exception){

        return false;

    }

}

}

但是,更好的解决方案是从控制器级别处理成功,因为它正在发出请求:

class Default_Model_Test extends Zend_Db_Table {

    public function updateTest($testId, $testData){

        $this->_db->update('test', $testData, array(
            'id = ?'        => $testId
        ));

    }

}

class Default_TestController extends Zend_Controller_Action {

    public function updateAction(){

        try {

            $testId = $this->_request->getParam('testId');
            if (empty($testId)) throw new Zend_Argument_Exception('testId is empty');

            $testData = $this->_request->getPost();
            if (empty($testId)) throw new Zend_Argument_Exception('testData is empty');

            $testModel->updateTest($testId, $testData);

        }
        catch (Exception $exception){

            switch (get_class($exception)){

                case 'Zend_Argument_Exception': $message = 'Argument error.'; break;
                case 'Zend_Db_Statement_Exception': $message = 'Database error.'; break;
                case default: $message = 'Unknown error.'; break;

            }

        }

    }

}

在处理多种资源类型、使用异常类型的开关以及根据程序的需要做适当的事情时,这是一个极好的解决方案。没有什么能逃脱这个真空。

于 2014-02-08T03:50:39.967 回答
0

也许:

$data = array(
    'updated_on'      => '2007-03-23',

    'bug_status'      => 'FIXED'
);
$result = $db->update('bugs', $data, 'bug_id = 2');
if ($result < $numRows) {//pass in numRows as method arg or hardcode integer.
    //handle error
} else {
    return TRUE;
}

尝试这样的事情,你想验证你想要更新的记录数量是否得到了更新。

于 2012-07-15T11:32:38.577 回答