[英]Codeigniter always only returning 1st row of the query result
Update 更新资料
I tried to use sizeof($result)
on my controller
and the result is more than 1, so i think the mistake is somewhere on the controller . 我试图在
controller
上使用sizeof($result)
,结果超过1,所以我认为错误出在控制器上 。
I tried to run this query : 我试图运行此查询:
$query = "SELECT * FROM `hospital` WHERE name LIKE '%$keyword%' OR address LIKE '%$keyword%' OR telp LIKE '%$keyword%'";
the $keyword
depends of what user type in the app. $keyword
取决于应用程序中的用户类型。
This is the CI query : 这是CI查询:
$query = $this->db->select('*')
->from($table)
->like('name', $keyword, 'both')
->or_like('address', $keyword, 'both')
->or_like('telp', $keyword, 'both')
->get()
->result_array();
The query above always only return the 1st row. 上面的查询始终只返回第一行。
This is in the controller : 这是在控制器中:
if(sizeof($result) > 0)
{
foreach($result as $hospital)
{
if($hospital)
{
$this->response(array('result' => 'true',
'id' => $hospital['id'],
'name' => $hospital['name'],
'address' => $hospital['address'],
'telp' => $hospital['telp']), 200); // 200 being the HTTP response code
}
}
}
else
{
$this->response(array('result' => 'false'), 404);
}
Where is my mistake? 我的错误在哪里? When i tried to hard type the query in the
phpmyadmin
, the query run perfectly (returning all row). 当我尝试在
phpmyadmin
硬键入查询时,查询运行完美(返回所有行)。
Thanks for your time 谢谢你的时间
You are assigning your query result to a $query
variable and then you are trying to iterate over $result
array that has not been declared anywhere. 您正在将查询结果分配给
$query
变量,然后尝试遍历尚未在任何地方声明的$result
数组。 Try: 尝试:
if(sizeof($query) > 0) {
// ...
}
or change the $query
to $result
. 或将
$query
更改为$result
。
Here is the another way to handle this requirement. 这是处理此要求的另一种方法。
$this->db->select('*')
->from($table)
->like('name', $keyword, 'both')
->or_like('address', $keyword, 'both')
->or_like('telp', $keyword, 'both');
$query = $this->db->get();
if ($query->num_rows() > 0) {
$result= $query->result_array();
//and bla bla
}
By using 通过使用
$query->num_rows()
we can return also total number of rows from model. 我们还可以返回模型的总行数。 You can also made chack in model class if num_rows is zero return false and check from controller if function return array or false.
如果num_rows为零,则还可以在模型类中使chack返回false,并从控制器检查函数的返回数组还是false。
I don't think you need ->result_array(); 我认为您不需要-> result_array();
->get() is good enough. -> get()足够好。
Remove all ->result_array() instances. 删除所有-> result_array()实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.