您好,我遇到以下问题,可以将每个查询的结果保存在数组中(查询 1、查询2、查询3)。 这是我的模型中的函数:
function get_query($year){
$query1 =$this->db->query("select count(*) as c from table where MONTH(date) = 1 AND YEAR(date) ='".$year."'");
$query2 =$this->db->query("select count(*) as c from table where MONTH(date) = 2 AND YEAR(date) ='".$year."'");
$query3 =$this->db->query("select count(*) as c from table where MONTH(date) = 3 AND YEAR(date) ='".$year."'")
}
我需要在驱动程序中以 json 格式接收该数组。
function query(){
$year = $_POST['year'];
$data = $this->mymodel->get_query($year);
echo json_encode($data);
}
这是我的 Controller :
最佳答案
这并没有回答您的问题,但我相信它向您展示了问题的解决方案,在模型中尝试
if (is_number($year))
{
$query = $this->db->query("select sum(if(month(date)=1 and year(date) = {$year},1,0)) as month1,
sum(if(month(date)=2 and year(date) = {$year},1,0)) as month2,
sum(if(month(date)=3 and year(date) = {$year},1,0)) as month3
from `table`");
return $query->first_row();
}
这应该将所有内容放入一个查询和一行中。 请注意,is_number 提供了一些注入(inject)预防功能。
要回答您的问题,您需要创建一个包含键和值的新数组,或者创建一个标准类来保存所有数据并将其返回到 Controller 。我认为这个解决方案更好,因为您只执行一个查询而不是三个。
关于php - 将多个查询的结果保存在 codeigniter 中的单个数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41510376/