php 如何使用Datamapper计算Codeigniter中查询返回的行数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10411386/
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
how to count the number of rows returned by query in Codeigniter with Datamapper
提问by Shashi Roy
I am using the following query in controller of codeigniter.
我在 codeigniter 的控制器中使用以下查询。
$u -> where('us_email_id', $username);
$u -> where('us_password', $password1);
$details = $u -> get();
$total = count($details);
echo $total; echo "<br>";
echo count($details);
In the above code "$u" is the object name for the class "User" for the datamapper "User" where the table name in my database is "users". I want to see how many rows are returned after executing the query. "$total" always displays 1 even if userid and password is not matched. What I want is , if number of rows returned 1 then "ok" else "something wrong". I know its basic but if somebody know it then please help me out. Thanks in advance.
在上面的代码中,“$u”是数据映射器“User”的“User”类的对象名称,其中我的数据库中的表名称是“users”。我想看看执行查询后返回了多少行。即使用户 ID 和密码不匹配,“$total”也始终显示 1。我想要的是,如果行数返回 1,则“确定”否则“出现问题”。我知道它的基本知识,但如果有人知道,请帮助我。提前致谢。
回答by TigerTiger
Following is availab in CI - checkout this page - http://codeigniter.com/user_guide/database/results.html
以下在 CI 中可用 - 查看此页面 - http://codeigniter.com/user_guide/database/results.html
$query->num_rows()
The number of rows returned by the query. Note: In this example, $query is the variable that the query result object is assigned to:
查询返回的行数。注意:在本例中,$query 是查询结果对象分配给的变量:
$query = $this->db->query('SELECT * FROM my_table');
echo $query->num_rows();
so that in your example above you need to try
所以在你上面的例子中你需要尝试
$details->num_rows();
回答by Kemal Fadillah
If you just want to count the total rows found, call the count()method instead of get().
如果您只想计算找到的总行数,请调用count()方法而不是get()。
$u->where('us_email_id', $username);
$u->where('us_password', $password1);
$total = $u->count();
But, if you also need the data, then you can simply call get(), and after that use PHP count()to count how many elements are there inside the allproperty of the object.
但是,如果您还需要数据,那么您可以简单地调用get(),然后使用 PHPcount()来计算all对象的属性内有多少元素。
$u->where('us_email_id', $username);
$u->where('us_password', $password1);
$u->get();
$total = count($u->all);
You can check out the documentation for more details.
您可以查看文档以获取更多详细信息。
回答by Prabhu Manickavelu
If the password was encrypted and try again
如果密码已加密,请重试
or if all the data part is fine the try to use the following code
或者如果所有数据部分都很好,请尝试使用以下代码
$this->db->where(array('us_email_id' => $username,'us_password' => $password1));
echo $this->db->count_all_results('users');

