简体   繁体   中英

Fetching data from relational database in codeigniter

I have got 2 tables; table1 and table2. Both of them are related to eachother with a common groupid I am able to query the second table successfully using the following code:

$query = $this->db->query("SELECT * FROM `table2` WHERE `memberid`='$id'"); 
$data['relation'] = $query->result_array(); 

Now using groupid result I want to query the first table ie table1

I have tried the following methods, without any success:

for($ii = 0 ; $ii < count($data['relation']) ; $ii++){
        $id = $data['relation'][$ii]['groupid'];
        $query1 = $this->db->query("SELECT * FROM `group` WHERE `id`='$id'");
}             

$data1['group'] = $query1->result_array();

$fine = array_merge($data, $data1);
print_r(count($fine)); // the count result is 1 ideally should be 2

The above code only returns the last row of the table1 however I am looking for all the results.

When I run the above code inside the "for" loop, it shows me a count of 33:

    for($ii = 0 ; $ii < count($data['relation']) ; $ii++){
        $id = $data['relation'][$ii]['groupid'];
        $query1 = $this->db->query("SELECT * FROM `group` WHERE `id`='$id'");

$data1['group'] = $query1->result_array();

$fine = array_merge($data, $data1);
print_r(count($fine)); // the count result is 33 ideally should be 2
}             

I know how to achieve this in core php however not too sure how to do it in CI. I am new to CI, any help will be greatly appreciated.

Thanks, Utpal

$ok = array();
     for($ii = 0 ; $ii < count($data['relation']) ; $ii++){
            $id = $data['relation'][$ii]['groupid'];
            print_r ($id);
            echo "<br>";
            $query1 = $this->db->query("SELECT * FROM `group` WHERE `id`='$id'");
            $data1['group'][$ii]= $query1->result_array();

    }
        //print_r($data1['group']);
        $fine = array_merge($data, $data1);
        print_r($fine);

You need to create a array ($data1) outside this for loop and define $query->result_array(); inside forloop as shown above

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