Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 受CI影响的_行即使在更新后也始终返回0_Php_Codeigniter_Model - Fatal编程技术网

Php 受CI影响的_行即使在更新后也始终返回0

Php 受CI影响的_行即使在更新后也始终返回0,php,codeigniter,model,Php,Codeigniter,Model,我使用Codeigniter 3.0.6构建了一个系统。 通常,我使用受影响的_rows()检查数据库是否更新 function update($id=0,$data=array()) { $this->db->where($this->key, $id); $this->db->update($this->table,$data); if($this->db->affected_ro

我使用Codeigniter 3.0.6构建了一个系统。 通常,我使用受影响的_rows()检查数据库是否更新

    function update($id=0,$data=array())
    {
        $this->db->where($this->key, $id);
        $this->db->update($this->table,$data);
        if($this->db->affected_rows() > 0)return TRUE;
        else return FALSE;
    }
问题是,如果找不到更新,它也将返回0。因为我想在代码中区分已更新和未更新,所以我使用这个解决方案

    function update($id=0,$data=array())
    {
        $this->db->trans_start();
        $this->db->where($this->key, $id);
        $this->db->update($this->table,$data);
        $this->db->trans_complete();
        if ($this->db->affected_rows() > 0) {
            return TRUE;
        } else {
            if ($this->db->trans_status() == FALSE) {
                return FALSE;
            }
            return 'No Update';
        }
    }
但即使在更新后,受影响的_行也始终返回int(0)。
原因是什么?谢谢。

我也在使用CI 3.0.6,受影响的行()会返回正确数量的更新行

您可以在没有事务的情况下进行测试吗。像这样的

function update($id)
{
    $this->db->set('field_name', "new_value");
    $this->db->where('id', $id);
    $this->db->update('table_name');

    $rows = $this->db->affected_rows();

    return $rows;
}
验证数据库中的记录是否已实际更新。您可以检查$行的更新状态

if ($rows < 1) {
    // no update
} else {
    // updated
}
if($rows<1){
//无更新
}否则{
//更新
}

如果将
$this->db->infected_rows()
移动到
$this->db->trans_complete()之前您将获得预期的计数。因为
受影响的行()
在您的问题中,它将返回
0

您可以通过将
$this->db->infected_rows()
分配到
$this->db->trans_complete()之前的另一个变量来修复此问题并稍后验证。


顺便提一下您只有一条语句,为什么要将其包装到事务中???@RahulM我想区分已更新和未更新,我在线搜索解决方案,这就是我目前得到的结果…CI2中受影响的行是否有任何问题,因为它总是在更新查询后给出0
function update($id=0,$data=array())
{
    $this->db->trans_start();
    $this->db->where($this->key, $id);
    $this->db->update($this->table,$data);
    $affected_rows = $this->db->affected_rows(); // moved to here from if condition
    $this->db->trans_complete();
    if ($affected_rows > 0) {
        return TRUE;
    } else {
        if ($this->db->trans_status() == FALSE) {
            return FALSE;
        }
        return 'No Update';
    }
}