使用codeigniter

时间:2016-05-11 05:52:48

标签: php mysql codeigniter

我无法使用codeigniter从数据库中检索类似的帖子数据。在我的blog中,我有一个标签字段,用于保存数据,例如' php,mysql,mongo,java,jquery'
我只是尝试获得与当前帖子标签相关的类似帖子。但我没有得到预期的结果。问题出在我的查询中。它只展示了三个帖子,即第一个,最后一个,第三个。

[CONTROLLER]

public function showpost()
{
    $data = array();            
    $this->load->view('header',$data);      
    $data['post'] = $query->result();
    $data['similar'] = $this->crudModel->getSimilarPost();
    $this->load->view('showfull',$data);
    $this->load->view('footer');
}

[MODEL]

public function getSimilarPost()
{
    $query = $this->db->get_where('blogs',array('id' => $this->uri->segment(3)));
    foreach($query->result() as $row){ $tags = $row->tags; }
    $match =  explode(',', $tags);
    for($i = 0; $i < count($match); $i++)
    {
        $this->db->like('tags',$match[$i]); 
        $this->db->from('blogs');
        $sqlQuery = $this->db->get();
    }       
    return $sqlQuery->result();
}

[VIEW]

foreach($similar as $row)
{
    echo($row->btitle.'<br/>');
}

1 个答案:

答案 0 :(得分:2)

试试这个。

public function showpost()
{
    $data = array();            
    $this->load->view('header',$data);      
    $data['post'] = $query->result(); // why this line??
    $data['similar'] = $this->crudModel->getSimilarPost();
    $this->load->view('showfull',$data);
    $this->load->view('footer');
}

[MODEL]

public function getSimilarPost()
{
    $query = $this->db->get_where('blogs',array('id' => $this->uri->segment(3)));
    foreach($query->result() as $row){ $tags = $row->tags }
    $match =  explode(',', $tags);
    $result = [];
    for($i = 0; $i < count($match); $i++)
    {
        $this->db->like('tags',$match[$i]); 
        $this->db->from('blogs');
        $sqlQuery = $this->db->get();
        if($sqlQuery->num_rows()>0)
        $result[] = $sqlQuery->result();
    }       
    return $result;
}

[VIEW]

$check = [];
foreach($similar as $row)
{
     foreach($row as $data)
     {
        if(!in_array($data->btitle,$check))
        {
            $check[] = $data->btitle;
            echo $data->btitle.'<br/>';
        }
     }
}