zend框架2 SQL更新并插入受影响的行(ZF2)

问题描述:

这是一个简单的问题,但我环顾四周,无法找到答案。 如何从ZF2中的更新/插入SQL查询中提取受影响的行数?zend框架2 SQL更新并插入受影响的行(ZF2)

下面的代码工作很好,我(它更新),但我想执行适当的错误检查:

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 
} 

目前,成功的时候,$结果是一个对象。我尝试了vardump,但没有显示出价值。

任何帮助,将不胜感激。谢谢。

+0

'$ result'希望应该是一个类型的'Result'。在这种情况下,这应该可以帮助你:https://github.com/zendframework/zf2/blob/master/library/Zend/Db/Adapter/Driver/Mysqli/Result.php#L150 - 如果没有,恐怕我帮不了你 – Sam 2013-02-15 08:08:02

+0

是的,就是这样。感谢您的链接。然后可以应用$ affectedRows = $ result-> getAffectedRows(); – dimmy 2013-02-15 08:32:38

你试过:

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

?据我记得,它包括可数的任何东西,其中包括affected_rows。

+1

+1,谢谢你帮助我很多 – Abhishek 2014-07-02 05:11:32

这里是正在运行的代码作为一个答案(因为它可以比在注释中找到更容易)

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

return $affectedRows;