php 在非对象上调用成员函数 num_rows()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20751899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call to a member function num_rows() on a non-object
提问by Renaud is Not Bill Gates
I'm using CodeIgniter, and I want to get some data from a table in a database.
我正在使用 CodeIgniter,我想从数据库的表中获取一些数据。
in my Model, I have this function :
在我的模型中,我有这个功能:
public function fetch_cours($limit, $start, $element) {
$id_element = $this->db->from('element')
->where('name',$element)
->limit(1)
->get()
->result();
$query = $this->db->from('cour')
->where('id_element',(int) $id_element[0]->id)
->limit($limit, $start)
->get()
->result();
var_dump($query);
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
I want this function to return some records in the courtable.
我希望这个函数返回cour表中的一些记录。
In my controller I have this line :
在我的控制器中,我有这条线:
$cours = $this->cours_m->fetch_cours(10,0,'Programmation Orientée Objet (Java)');
When I call my controller I get this message :
当我打电话给我的控制器时,我收到这条消息:


The line 38 is : if ($query->num_rows() > 0) {
第 38 行是: if ($query->num_rows() > 0) {
So I did a var_dump($query) and this is the output :
所以我做了一个 var_dump($query) ,这是输出:


What's the problem ? and how can I solve it ?
有什么问题 ?我该如何解决?
回答by Lajos Veres
When you create the $queryvariable you already added a ->result().
创建$query变量时,您已经添加了一个->result().
So $queryis an array of row objects.
$query行对象数组也是如此。
You should change the ifto this:
您应该将其更改if为:
if (count($query) > 0) {
And probably rename the variable to $resultsfor example.
并且可能将变量重命名$results为例如。
回答by maphe
Calling ->result(), you have the result of the query execution in an array. You might call your variable like this, for example :
调用 ->result(),您将获得一个数组中的查询执行结果。您可以像这样调用变量,例如:
$cours = $this->db->from('cour')
->where('id_element',(int) $id_element[0]->id)
->limit($limit, $start)
->get()
->result();
Then change your test as :
然后将您的测试更改为:
if (count($cours) > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}

