简体   繁体   中英

Save result of many queries in a single array in codeigniter

Hi I have the following problem, it is possible to save the result of each of the queries in an array (query 1, query2, query3). This is the function in my model:

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."'")


}

And I need to receive that array in the driver in json format.

function query(){

        $year = $_POST['year'];
        $data = $this->mymodel->get_query($year);
        echo json_encode($data);
    }

This is my controller:

this is not answering your question but i believe that it is showing you a solution to the issue, in the model, try

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();
}

that should get it all into one query and one row for you. note that is_number provides some injection prevention.

to answer your question, you would need to make a new array with keys and values, or create a standard class that holds all the data and return it to the controller. I think this solution is nicer because you are doing one query and not three.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM