zend framework 2 SQL更新并插入受影响的行(ZF2) [英] zend framework 2 SQL update and insert affected rows (ZF2)

查看:145
本文介绍了zend framework 2 SQL更新并插入受影响的行(ZF2)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的问题,但我环顾四周,找不到答案. 如何从ZF2中的更新/插入SQL查询中提取受影响的行数?

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
}

当前,成功时,$ result是一个对象.我试图进行包装,但没有显示出值.

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.

推荐答案

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

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;

这篇关于zend framework 2 SQL更新并插入受影响的行(ZF2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆