检查CI查询是否有结果

时间:2014-01-01 03:28:38

标签: php mysql codeigniter activerecord

我在useraccount模型中有以下功能

public function verification_status($balpaycustid){
    $result = $this->db->where('active',1)->where('locked',0)->where('balpaycustid',$balpaycustid)->get('useraccount')->row();
    return $result;
}

这将返回以下对象(如果有结果)

stdClass Object
(
  [id] => 3
  [verified] => 
  [active] => 1
  [locked] => 0
  [account] => 123456790
)

如果没有结果,我更喜欢这个函数会返回FALSE,尽管我不完全确定如何做到这一点。想法?

3 个答案:

答案 0 :(得分:7)

虽然稍微夸大了你的方法,但你可以使用num_rows在返回之前检查是否有结果。

有些事情:

public function verification_status($balpaycustid){

    $result = $this->db->where('active',1)->where('locked',0)->where('balpaycustid',$balpaycustid)->get('useraccount');

    if ($result->num_rows()) {
        return $result->row();
    } else {
        return false;
    }

}

答案 1 :(得分:2)

尝试此操作,使用num_rows()计算您拥有的记录数

public function verification_status($balpaycustid){
    $result = $this->db->where('active',1)->where('locked',0)->where('balpaycustid',$balpaycustid)->get('useraccount')->row();

    return ($result->num_rows() > 0)? 1 : 0;
}

答案 2 :(得分:0)

实施方面的改进

  1. 这可以写成返回的单线,但是行太长了。我可能会声明一个WHERE条件数组,以将代码保持在合理的宽度。
  2. get_where()将在一个整洁的方法调用中将表名作为第一个参数,然后将WHERE子句条件的关联数组作为第二个参数。
  3. row()将返回一个已填充的对象或null
  4. 由于您希望在不生成任何对象的情况下return false,因此只需使用null coalescing operator(自PHP7.0起可用)即可简洁地执行此转换。
  5. 有效地,没有理由额外拨打num_rows()

建议的代码段:

public function verification_status($balpaycustid) {
    $conditions = ['active' => 1, 'locked' => 0, 'balpaycustid' => $balpaycustid];
    return $this->db->get_where('useraccount', $conditions)->row() ?? false;
}