Codeigniter:在非对象上调用成员函数result_array()

时间:2013-08-21 00:29:56

标签: php codeigniter

我正在使用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';

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

由于get_all_contacts已在模型中使用result()函数,因此您不能在控制器中使用result_array()函数。 result_array()将是$ query对象的一个​​方法。让这个工作的快速而肮脏的方法(如果它也使用get_all_contacts方法可能会破坏其他东西)将把你的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();
}