0

My model has a function that should run 2 different queries.

Ideally I would like it to return 2 different vars (1 from each query) that would be available to my controller.

The code below obviously doesn't work b/c the first return ends execution right there. But how could I do something that would generate these two results within the same function?

Thanks for any help / pointer you can provide.

MODEL -- Hypothetical code

function ABC() 
{
    $query1 = $this->db->query( ... MySQL code #1 here ... );

    $data1 = array();
    foreach (query1->result() as $row){
        $data1[$row->k] = $row->value;

    return $data1;    

    $query2 = $this->db->query( ... MySQL code #2 here ... );

    $data2 = array();
    foreach (query2->result() as $row){
        $data2[$row->k] = $row->value;

    return $data2;
}
pepe
  • 9,799
  • 25
  • 110
  • 188

4 Answers4

4
function ABC() 
{
    $query1 = $this->db->query( ... MySQL code #1 here ... );

    $data = array();
    foreach (query1->result() as $row){
        $data['query1'][$row->k] = $row->value;


    $query2 = $this->db->query( ... MySQL code #2 here ... );

    $data2 = array();
    foreach (query2->result() as $row){
        $data['query2'][$row->k] = $row->value;

    return $data;
}

also see danip's answer

fazo
  • 1,807
  • 12
  • 15
  • @fazo -- thanks - should line 5 be `$data1` instead of `$data`? – pepe Apr 02 '11 at 21:08
  • @torr no - you need to have both results in one array – fazo Apr 02 '11 at 21:09
  • @fazo for the sake of sticking to best practices and letting others know what they are, I'm going with @danip's answer -- but thanks much for your suggestion -- greatly appreciated – pepe Apr 02 '11 at 21:34
  • @torr, i was just answering on how to return 2 query results in 1 array; if danip's answer works better for you, then i'm completely fine :) – fazo Apr 02 '11 at 21:42
  • thanks for understanding - at the end I refactored the model/controller code to avoid using an array to pass 2 query results – pepe Apr 02 '11 at 22:23
3

Got anything against return array($data1, $data2); ?

Then you could use list($foo, $bar) = $baz->ABC(); in your controller of you want to.

Darsstar
  • 1,885
  • 1
  • 14
  • 14
2

You can do this like fazo suggested but your class/method design seems to have a problem. You would be better of refactoring this code and return the results in two different functions.

johnlemon
  • 20,761
  • 42
  • 119
  • 178
0

Use the following Code Tested And Works fine

function Submit() 
{
    $query1 = $this->db->query( INSERT INTO... MySQL code #1 here ... );

    $query2 = $this->db->query( INSERT INTO... MySQL code #2 here ... );

    return array( $query1, $query2);
}

or

function Submit() 
{
    $query1 = $this->db->query( INSERT INTO... MySQL code #1 here ... );

    $query2 = $this->db->query( INSERT INTO... MySQL code #2 here ... );

    return $query1;
    return $query2;
}