如何在codeigniter数据库查询中跳过已删除的记录

时间:2018-05-13 10:27:48

标签: php codeigniter

在一个项目中,我正在显示最近查看/搜索的商店名称,以便客户快速访问它。我直接从数据库中删除了一些商店。在显示最近搜索的商店详细信息时,我收到此错误消息“试图获取非对象的属性”。已粘贴下面的代码。

<?php if(user_logged_in()){ ?>
     <?php $recent = $this->db->select('user_id,shop_id')
                     ->where('user_id',get_session('userid'))
                     ->distinct('user_id')->distinct('shop_id')
                     ->get('recent_view')->result(); ?>
     <?php if(!empty($recent)){ ?>
           <div class="recent shop_list_area" >
                <span class="greypara grey">Recent search</span>

                <ul class="list-group">
                    <?php foreach($recent as $k): ?>
                    <?php $shop = $this->db->where('id',$k->shop_id)
                                  ->get('shop_list')->row(); ?>
                    <?php $idfe = $this->db->where('user_id',$k->user_id)
                                 ->where('shop_id',$shop->id)->get('feedback')->row(); ?>

                    <?php if(empty($idfe)){ ?>
                    <?php if(!empty($shop)){ ?> 

2 个答案:

答案 0 :(得分:0)

在您的函数中添加此代码

public function Your_Method(){
    $query = $this->db->select('user_id,shop_id')->where('user_id',get_session('userid'))->distinct('user_id, shop_id')->get('recent_view');
    $recent = ($query->num_rows() > 0) ? $query->result() : false;
    $this->load->view('Your_view_file', compact('recent'));
}

现在$recent将从数据库返回结果,现在在视图文件中调用之前检查它

if($recent && array_filter($recent)){
  // your code            
}else{
  echo 'empty result';
}

答案 1 :(得分:0)

  

我收到此错误消息&#34;试图获取该属性   非对象&#34 ;.粘贴了下面的代码。

<强> 原因

It's because some of your queries are empty.

您所犯的错误如下:

  • ->get('recent_view')->result();
  • ->get('feedback')->row();

如果没有确定,您的查询返回了行,您正在调用result()/row()

我们无法确保查询将始终产生依赖于您所做的数据库表和查询​​的结果,假设您的查询未返回任何结果,则它无法调用row()result()方法。

你需要做的是,将所有方法链接到get('your_table')并将其分配给某个变量说$query,然后确保你有一些记录

$query = $this->db->select('user_id,shop_id')
                  ->where('user_id',get_session('userid'))
                  ->distinct('user_id, shop_id')
                  ->get('recent_view');

if( $query->num_rows() > 0 ){

     // here you call either $query -> result() ; $query->row();
     // depending on your requirement.

}else {

    // throw new Exception("No records found");

}