zen zen - 5 months ago 9
MySQL Question

Foreach loop with two queries inside

I have two queries which is working fine and it would retrieve 3 rows each query. I am trying to display a query result on a table using foreach with two(2) queries inside a foreach loop. I tried putting two result() on foreach but its an error. How can i display a two result() on a single foreach loop? I don't know how can i achieve this.

Query 1 would be on column "Investor Name" then query 2 will be on "Amount".

Here is the code:

<?php

$query5 = $this->db->query("SELECT * FROM ".tbl_investors." WHERE id IN (SELECT MAX(investor_id) FROM ".tbl_investors_ledger." GROUP BY investor_id ) AND deleted = 0");

$query6 = $this->db->query("SELECT * FROM ".tbl_investors_ledger." WHERE id IN (SELECT MAX(id) FROM ".tbl_investors_ledger." GROUP BY investor_id ) AND deleted = 0");

?>

<table class="table table-striped table-bordered table-hover" id="dataTables">
<thead>
<tr>
<td>Investor Name</td>
<td>Amount</td>
</tr>
</thead>
<tbody style="text-align: center;">

<?php
foreach ($query5->result() as $row) && ($query6->result() as $row2){
?>
<tr>
<td><?php echo $row->last_name.', '.$row->first_name; ?></td>
<td><?php echo $row2->amount; ?></td>
</tr>
<?php } ?>

</tbody>
</table>

ASR ASR
Answer

You can't use two array_expressions on foreach loop. It is better to use join on your query to make it one. something like

$query = "SELECT `tbl_investors`.* , `tbl_investors_ledger`.*  
 FROM `tbl_investors` 
 LEFT JOIN  `tbl_investors_ledger` 
 ON `tbl_investors`.id = `tbl_investors_ledger`. investor_id 
 WHERE `tbl_investors`.deleted = 0 AND `tbl_investors_ledger`.deleted = 0 
 GROUP BY `tbl_investors_ledger`.investor_id 
 ORDER BY `tbl_investors_ledger`.id DESC ";
Comments