我在查询结果中创建表时遇到问题。 我有这段代码:
// 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 :(得分: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类的代码,然后我会更新我的答案。
参考文献: