2

我正在使用 Codeigniter 构建一个 webapp,但我收到了这个错误:

Fatal error: Call to a member function result_array() on a 
non-object in /var/www/application/controllers/people.php on line 29

这是 people.php 类:

public function __construct()
{
    parent::__construct();
}

function People() {

}

function view($id) {
    echo "Hello world " . $id;
}

function all() {
    $this->load->model('people_model', '', TRUE);
    $allContacts = $this->people_model->get_all_contacts();
    $results = array();
    foreach ($allContacts->result_array() as $row) {
        $eachrow = array("personID"=>$row['personID'],"fName"=>$row['fName'],"lName"=>$row['lName'],"phoneNumber"=>"",
            "emailAddress"=>$row['emailAddress'],"address"=>$row['address'],"city"=>$row['city'],"state"=>$row['state'],"zip"=>$row['zip']);
        $results = push_array($results, $eachrow);
    }
    foreach ($results as $row) {
        $phoneData = $this->people_model->get_phone_by_id($row['personID']);
        $phoneNumbers = "";
        foreach ($phoneData->result_array() as $row2) {
            $phoneNumbers = $row2['type'] . " " . $row2['phoneNumber'] . " " . $row2['extension'];
        }
        $results['phoneNumber'] = $phoneNumbers;
    }

    $data['title']="Page Title Goes Here";
    $data['username']="Your Username";

    $this->load->view('header', $data);
    $this->load->view('people_results', $results);
    $this->load->view('footer');
}
}

这是 people_model 类:

function __construct()
{
    // Call the Model constructor
    parent::__construct();
}

function get_all_contacts() {
    $query = $this->db->query('SELECT * FROM person');
    return $query->result();
}

function get_phone_by_id($id) {
    $query = $this->db->query('SELECT * FROM phoneNumber WHERE personID = '.$id);
    return $query->result();
}
}

我在 database.php 中唯一可能提出的问题是主机名是否需要端口号,但我认为这在我尝试时没有帮助。

我刚刚尝试添加(基于侧栏中的类似问题)

$this->mydb = $this->load->database('realDB', TRUE);

到 people_model 并将 db 更改为 mydb 并收到此错误:

You have specified an invalid database connection group.

这是我在 database.php 中的一行:

$db['default']['database'] = 'realDB';

感谢你的帮助。

4

1 回答 1

2

由于 get_all_contacts 已经在您的模型中使用了 result() 函数,因此您也不能在控制器中使用 result_array() 函数。result_array() 将是 $query 对象的方法。让这个工作的快速而肮脏的方法(如果它也使用 get_all_contacts 方法可能会破坏其他东西)是将你的获取所有联系人功能更改为以下内容:

function get_all_contacts() {
    $query = $this->db->query('SELECT * FROM person');
    return $query;
}

但是,如果您想更聪明一点并且不冒破坏其他东西的风险,您可以从控制器传递一个参数,并且仅在其设置如下时才返回查询:

修改后的控制器线**

$allContacts = $this->people_model->get_all_contacts(true);

修订的模型代码

function get_all_contacts($special = false) {
    $query = $this->db->query('SELECT * FROM person');
    if($special)
    {
        return $query;
    }
    return $query->result();
}
于 2013-08-21T01:25:03.367 回答