查询只返回一行数据

时间:2011-08-16 15:59:37

标签: php sql codeigniter

我在codeigniter中创建了一个Web应用程序,它根据用户添加到关键字列表中的关键字为用户检索数据库中的帖子。 我试图用user关键字检索所有帖子但是,它只返回一个帖子,而帖子中的关键字有多个匹配

这是我的模型中的函数

此函数检索用户关键字

function user_keywords($user_id) {
         //Get all the user keywords
         $q = $this->db->select('keywords')
                        ->from('keywords')
                        ->where('U_id',$user_id)
                        ->get();
        $words = $q->result_array();
        return $words;
     }

此功能检索帖子

function get_latest_pheeds() {
        $this->load->helper('date');
         $time = time();
         $keyword = $this->user_keywords($this->ion_auth->user_id);
         foreach($keyword as $word) {
         $q = $this->db->select('user_id,pheed_id,datetime,pheed,COUNT(pheed_comments.comment_id) as comments')
         ->from('pheeds')
         ->join('pheed_comments','pheed_comments.P_id=pheeds.pheed_id','left')
         ->like('pheed',$word['keywords'])
         ->order_by('datetime','desc')
         ->get();
         }
         $rows = $q->result_array();
         return $rows;
     }

我的控制器用JSON编码它

function latest_pheeds() {
            if($this->isLogged() == true) {
            $this->load->model('pheed_model');
            $data = $this->pheed_model->get_latest_pheeds();
            echo json_encode($data);
            }
            return false;
    }

我非常感谢帮助

1 个答案:

答案 0 :(得分:1)

我认为(但没有测试很难)问题来自函数get_last_feeds:

您的查询是在每个循环的迭代中构建的,但您在之后获取结果。我认为你只得到最后一个查询的结果(如果你没有在每个循环上获取结果,下一次迭代会覆盖原始请求而不会获取它的结果)。

我会做这样的事情:

<?php
function get_latest_pheeds() {
     $rows = array(); // The final result, an array of rows
    $this->load->helper('date');
     $time = time();
     $keyword = $this->user_keywords($this->ion_auth->user_id);
     foreach($keyword as $word) {
     $q = $this->db->select('user_id,pheed_id,datetime,pheed,COUNT(pheed_comments.comment_id) as comments')
     ->from('pheeds')
     ->join('pheed_comments','pheed_comments.P_id=pheeds.pheed_id','left')
     ->like('pheed',$word['keywords'])
     ->order_by('datetime','desc')
     ->get();
     $rows[] = $q->result_array();
     }

     return $rows;
 }
相关问题