zend framework 2 SQL update and insert affected rows (ZF2)

烂漫一生 提交于 2019-12-24 20:42:09

问题


This is a simple question, but I've looked around and couldn't find the answer. How do I extract the number of affected rows from update/insert SQL queries in ZF2?

The following code is working nicely for me (it does update), but I would like to perform proper error checks:

public function updateSomeField($id, $some_field){
    $data = array(
        'some_field'  => $some_field
    );

    $sql = new Sql($this->dbAdapter);
    $update = $sql->update();
    $update->table('Table1');
    $update->set($data);
    $update->where(array('id' => $id));
    $statement = $sql->prepareStatementForSqlObject($update);

    // need help with the code below...
    // got this from here:
    // http://stackoverflow.com/questions/11491249/zend-framework-db-update-result
    $result = 0;
    try {
        $result = $statement->execute();        // works fine
    } catch (\Exception $e) {
        die('Error: ' . $e->getMessage());
    }
    if (empty($result)) {                       // not sure if this is applicable??
        die('Zero rows affected');
    }

    return $result;                             // ideally, I'd like to return $numRows
}

Currently, when successful, $result is an object. I tried to vardump it, but it's not showing up the values.

Any help would be appreciated. Thanks.


回答1:


Have you tried:

if ( $result->count() === 0 ) {
  die('Zero rows affected');
}

? As far as I remember, it counts anything countable, affected_rows included.




回答2:


Here is the running code as an answer (because it can be found easier than in comments)

try {
    $affectedRows = $statement->execute()->getAffectedRows();
} catch (\Exception $e) {
    die('Error: ' . $e->getMessage());
}
if (empty($affectedRows)) {
    die('Zero rows affected');
}

return $affectedRows;


来源:https://stackoverflow.com/questions/14890247/zend-framework-2-sql-update-and-insert-affected-rows-zf2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!