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>
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 ";
As far as I know, a foreach loop can only handle one query. I see two options out of this, really..
Option 1
Create two different foreach loops, not inside each other since that would make double results, but outside each other. That might not do what you want to, but it could be worth a shot, like so:
<!-- FIRST LOOP -->
<?php
foreach ($query5->result() as $row) {
?>
<td> Your data goes here </td>
<?php
}
?>
<!-- SECOND LOOP -->
<?php
foreach ($query6->result() as $row) {
?>
<td> Your data goes here </td>
<?php
}
?>
Option 2
Create only one query, requiring only one of the loops, by taking use of "JOIN"
See answer at this post