2016-03-07 22 views
0

我無法得到相應的結果 我需要得到一個表的結果,這種方式SQL結果從另一個表包括子場

$catid=$_POST['category']; 
$new_id = select catid from categories_table where catid='$catid' and parent='$catid'; 

所以它會增加還包括其他貓的結果$ cadid父

Select * from articles_table where catid = '$new_id'; 

我試圖在笨這樣

$p=$this->input->post('category'); 
    $this->db->select('catid'); 
    $this->db->where('parent',$p); 
    $this->db->where('catid',$p); 
    $query = $this->db->get('categories_table'); 

    if($query->num_rows()>0) 
      { 
      foreach($query->result() as $row) 
      $new_id[]=$row->catid; 
      } 
    $this->db->where('catid',$new_id); 
    $this->db->where('status',1); 
    $this->db->order_by('time_added', 'desc'); 
    $res = $this->db->get('articles_table'); 
    $query_res= $res->result(); 

它給人的錯誤Message: Trying to get property of non-object

cats table 
catid -- parent -- name 
1  -- 0   -- first cat 
2 --  1   -- cat child of first 

Article table 
id -- catid - content 
1 -- 2  -- first article 
2 -- 1  -- second article 

如果我查詢,其中貓ID = 1,它應該返回從CATID 2的結果也爲2是一個

+0

只是想提醒你,你調用$ query-> result()兩次。嘗試刪除其中的一個。像foreach($ query爲$ row){...}或者刪除之前的一個if – Jaaaaaaay

+0

另外,你在num_rows後錯過了括號,它應該是if($ query-> num_rows()> 0),我建議你可以需要仔細閱讀codeigniter文檔,它會爲您節省大量時間。 – Jaaaaaaay

+0

還有一個錯誤是,它可能應該是'$ new_id [] = $ row-> catid;'。 – Tpojka

回答

1

孩子,我會嘗試使用模式是這樣的:

$p = $this->input->post('category'); 
$query = $this->db 
    ->select('catid') 
    ->where('parent',$p) 
    ->or_where('catid',$p) 
    ->get('categories_table'); 

$data = array(); 
if($query->num_rows()) 
{ 
    foreach($query->result() as $row) 
    { 
     $res = $this->db 
      ->where('catid',$row->catid) 
      ->where('status',1) 
      ->order_by('time_added', 'desc') 
      ->get('articles_table'); 
     foreach ($res->result() as $article_data) 
     { 
      $data[] = $article_data; 
     } 
    } 
} 
return $data; 

代碼首先檢查類別,其中$p要麼等於catid或categories_table parent。然後檢查與該類別具有相同catid的文章,並將所有文章添加到數組$data