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

ブール値の戻り値を探しているだけの場合、このソリューションはモデルでの成功を処理するのに最適です。

class Default_Model_Test extends 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 に答える