[英]codeigniter single result without foreach loop
I am using codeigniter to get a single result from the db, like this: 我正在使用codeigniter从数据库中获取单个结果,如下所示:
$user = $this->db->query("SELECT * FROM users LIMIT 1");
I am then getting the returned object and looping trough it, this way: 然后,我以这种方式获取返回的对象并循环通过它:
foreach ($user->result() as $row) { ... }
As you can imagine, there is not point in using the loop, since there is only one result. 可以想象,使用循环是没有意义的,因为只有一个结果。 Is there a way to get users parameters without looping?
有没有一种方法可以获取用户参数而不循环? Something among this line:
此行中的内容:
echo $user['name'];
Thanks in advance. 提前致谢。
$user = $this->db->query("SELECT * FROM users LIMIT 1")->row();
for having it as an object ( echo $user->name;
) 将其作为对象(
echo $user->name;
)
$user = $this->db->query("SELECT * FROM users LIMIT 1")->row_array();
for having is as an array ( echo $user['name'];
); 因为具有作为数组(
echo $user['name'];
);
$user = $this->db->limit(1)->get('users')->row(); //or ->row_array();
using AR; 使用AR;
$row = $user->first_row();
to get the first row out of a result set ($this->db->result()), as an object (default); 从结果集中获取第一行($ this-> db-> result())作为对象(默认);
$row = $user->first_row('array');
to get the first row out of a result set, as an array; 从结果集中获得第一行作为数组;
$row = $user->row_array(1);
to return a specific row (first, in this case. Just pass the <N>
of the row). 返回特定的行(在这种情况下,首先返回。只需传递该行的
<N>
)。 Works also for $user->row(1);
也适用于
$user->row(1);
It would be: 这将是:
$user = $this->db->query("SELECT * FROM users LIMIT 1")->row_array();
More details here: http://ellislab.com/codeigniter/user-guide/database/results.html 此处有更多详细信息: http : //ellislab.com/codeigniter/user-guide/database/results.html
do something like this 做这样的事情
//in the model
$query = $this->db->query("your query");
$row = $query->row();
if (isset($row))
return $row;
}else{
return false;
}
then echo your results like this 然后像这样回显你的结果
echo $row->username;
if you want to pass it to a view 如果您想将其传递给视图
//in the controller
$this->load->model('somemodel');
$hm=$this->somemodel->somemethod();
$data['query']=$hm;
$this->load->view('path/to/view',$data);
Then echo the same way 然后以相同的方式回声
echo $row->username;
Suppose for example your model function is like this....... 例如,假设您的模型函数是这样的……
public function get_users()
{
$query = "Select * from users limit 1";
$res=$this->db->query($query);
if($res->num_rows()>0){
return $res->result("array");
}
return array();
}
Suppose you are calling this model in your controller function like this 假设您正在像这样在控制器函数中调用此模型
$users = $this->model_file->get_users();
then you can echo like this echo $users[0]['user_name'];
然后您可以像这样
echo $users[0]['user_name'];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.