返回查询结果和行数 [英] Return both query result and num rows

查看:61
本文介绍了返回查询结果和行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 MySQL 和 PHP 使用 MVC CodeIgniter.常见情况 - 我从数据库中获取数据,我想对它们进行计数.我想知道我怎样才能以最优化的方式做到这一点.在一个函数中这样做是否明智?

I'm working in MVC CodeIgniter with MySQL and PHP. Common case - I get data from database and I want count of them. I wonder how can I do it in the most optimial way. Is it sensible to do it in one function?

我将与您分享我的解决方案,请告诉我这是一个好方法.假设我们有一个模型函数:

I will share with You my solution and please tell me is it a good approach. Let's say we have a Model function:

public function get_results()
{
   $query = $this->db->get('data');
   $result = $query->result();
   $count = $query->num_rows();
   return [$result, $count];
}

以这种方式返回两个值是不是很愚蠢?

Question isn't that silly to return both values that way?

我想避免创建新函数 num_result() 因为我已经运行了一个,所以只为计数行执行另一个 SQL.有没有其他有效的方法可以从一次查询执行中获取计数?

I want to avoid creating new function num_result() executing another SQL for only count rows since I have already ran one. Is there any other effective way to take count from one query execution?

推荐答案

你也可以使用你的函数:

also you can use your function:

public function get_results()
{
   $query = $this->db->get('data');
   $result = $query->result();
   return $result
}

然后调用函数时:

$result= $this->your_model->get_results();
$count = count($result);

这篇关于返回查询结果和行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆