2011-04-10 50 views
0

我在查詢結果中創建表時遇到問題。 我有這樣的代碼:需要幫助從查詢結果創建表

// Model 
<?php 
    class Search_Employee extends CI_Model { 
     function getAll() { 
      $searchterm = $this->name = $_POST['empname']; 

      $this->db->like('first_name', $searchterm); 
      $this->db->or_like('last_name', $searchterm); 

      $q = $this->db->query("SELECT first_name, last_name, deparment.name FROM employee 
            INNER JOIN deparment ON employee.department_id = department.id 
            WHERE first_name LIKE '%" . $searchterm . "%' OR last_name LIKE '%" . $searchterm . "%'"); 

      if ($q = $this->db->get('employee')) 
      { 
       if ($q->num_rows() > 0) { 
        foreach ($q->result() as $row) { 
         $data[] = $row; 
        } 
        return $data; 
       } else { 
        echo "No results found."; 
        return array(); 
       } 
      } else { 
       echo sprintf("DB Query Failed: %s", $q); 
       return false; 
      } 
     } 
    } 

// Controller 
class Employees extends CI_Controller { 
    function search_employee() 
    { 
     $this->load->library('table'); 
     $this->load->model('search_employee'); 

     $data['main_content'] = 'display_employee'; 
     $data['rows'] = $this->search_employee->getAll(); 

     $this->load->view('includes/template', $data); 

    } 

} 

// View 
<h1>Results</h1> 
<?php 
$this->table->set_heading('Name', 'Last Name', 'Department'); 
$tmp = array ('table_open' => '<table border="0" cellpadding="2" cellspacing="1">'); 
$this->table->set_template($tmp); 

foreach ($rows as $r) : 
    $this->table->add_row($r); ?> 
endforeach; 
?> 

我不斷收到一個

Fatal error: Call to a member function result() on a non-object in C:\xampp\htdocs\employees\application\views\display_employee.php on line 15 
Line 15 

foreach()循環。

非常感謝您的幫助。

+0

是查詢返回結果?可能是發生錯誤,並且getAll函數返回false。 – Zoidberg 2011-04-10 16:10:11

+0

我也想補充一點,你的查詢讓你打開SQL注入攻擊。 – Zoidberg 2011-04-10 16:10:46

+0

是的,查詢返回結果。 – ebecker 2011-04-10 16:28:11

回答

0

我不知道什麼類$this->db對象指的是,它似乎也不是mysql,也不是mysqli或PDO。順便說一句,$this->db->get('employee')似乎沒有返回一個對象。

也許你犯了一個錯字,你的意思是$this->db->result()這可能是一個返回你最後一個查詢結果的函數。

你也可以檢查(if (is_object($q)) {})如果$q是對象之前對待它像它一樣。

你爲什麼不更換

foreach ($q->result() as $row) { 
    $data[] = $row; 
} 

$data = $q->result;

如果您想了解更多信息,最好添加一些關於此DB類的代碼,那麼我會更新我的答案。

參考文獻:

+0

即時引用codeigniters數據庫類:http://codeigniter.com/user_guide/database/examples.html – ebecker 2011-04-10 16:36:05

+0

@ebecker,爲什麼你選擇結果(第一個查詢)到'$ q'來代替它們'if($ q = $ this-> db-> get('employee'))'? – Shoe 2011-04-10 16:38:49