Foreach loop with two queries inside - php

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

Related

Dynamic row span php while loop

i have two tables one item table and customer table:
in the table you can see the second item item id 1002 have two entries.and i want to add colspan to that item for column 1 and 3.
<table>
<tr>
<th>Item ID</th>
<th>Item Color</th>
<th>Customer</th>
</tr>
<?php
$sql = mysqi_query($con,"select * from item_table");
while($row = mysqli_fetch_array($sql)){
?>
<tr>
<td><?=$row['item_id'];?></td>
<td><?=$row['item_color'];?></td>
<td>
<select>
<?php
$sql_cust = mysqli_query($con,"select * from customer_tbl");
while($row_cust = mysqli_fetch_array()){
if($row['customer_id'] == $row_cust['customer_id']){
echo "<option selected='selected' >".$row['customer_name']."</option>";
}else{
echo "<option>".$row['customer_name']."</option>";
}
<?php
}
?>
</select>
</td>
</tr>
<?php
}
?>
</table>
But it print in normal way, i have no idea how to add rowspan in loop..please suggest some logic to solve its appreciated.
You can try it this way:
First, add a counter to your query that will indicate how many entries has a given item.
$sql_cust = mysqli_query($con,
"SELECT *, (SELECT COUNT(*) FROM item_table as it
WHERE it.item_id = item_table.item_id) as c
FROM item_table");
Then, when looping through the items you will set the rowspan to the number of entries the item has. Below is the whole code adjusted.
<?php
$sql = mysqi_query($con,
"SELECT *, (SELECT COUNT(*) FROM item_table as it
WHERE it.item_id = item_table.item_id) as entry_count
FROM item_table");
$buffer = [];
while($row = mysqli_fetch_array($sql)){
if(!isset($buffer[$row[$item_id]])) {
$buffer[$row[$item_id]] = 1;
}
?>
<tr>
<?php if(!isset($buffer[$row[$item_id]])) {?>
<td rowspan="<?=$row['entry_count']?>"><?=$row['item_id'];?></td>
<?php }?>
<td><?=$row['item_color'];?></td>
<?php if(!isset($buffer[$row[$item_id]])) {?>
<td rowspan="<?=$row['entry_count']?>">
<select>
<?php
$sql_cust = mysqli_query($con,"select * from customer_tbl");
while($row_cust = mysqli_fetch_array()){
if($row['customer_id'] == $row_cust['customer_id']){
echo "<option selected='selected' >".$row['customer_name']."</option>";
}else{
echo "<option>".$row['customer_name']."</option>";
}
<?php
}
?>
</select>
</td>
<?php }?>
</tr>
<?php
}
?>
Note that I added a buffer where I set which item was already displayed. That array is used so you only open one td with the wanted rowspan, instead of doing it on every iteration.
i have a simple idea
give TD a ID like
<td id="dynamically-Generate"> (you need to verify that TD id need to be equal in .rowSpan ="here" inside script )
and set this TD if dynamically-Generate is greater than 1 then don't show
and again if dynamically-Generate is greater than 1 then then use this script
<script>
document.getElementById("dynamically-Generate").rowSpan = "dynamically-Generate";
</script>
use script inside loop and both dynamically-Generate need to be same inside everyloop and change after each loop

Working with two tables and grouping in mysql and php

I have two tables like this.
books
=====
b_id a_id book_name
1 1 ABC
2 1 DEF
3 2 GHI
authors
=======
a_id author_name
1 A1
2 A2
I need a table like this.
S.No BookName
-----------------
A1
==
1 ABC
2 DEF
A2
==
1 GHI
What i'm planning to do is
1. Do a while loop and get the author name first and print it
2. Use the author id inside the first loop and do another one iteration to get the list of book list for each author.
A sample code is like this:
<table cellpadding="0" cellspacing="0" border="0">
<thead>
<tr>
<th>S.No</th>
<th>Book Name</th>
</tr>
</thead>
<?php
$mysql_query1 = "my sql query to get the author name list first";
$results = mysql_query ( $mysql_query1 ) or die ( mysql_error () );
while($row = mysql_fetch_array($results)){
?>
<tbody>
<tr>
<td style="background:none;"><u><?php echo $row['author_name']; ?></u></td>
</tr>
<?php
$result = mysql_query ( "mysql query to get the list of books for each author with a where condition like this where a_id=$row['a_id']" ) or die ( mysql_error () );
$book_count = mysql_num_rows($result);
while($row1 = mysql_fetch_array($result)){
?>
<tr>
<?php for($i=1;$i<=$book_count;$i++){ ?>
<td><?php echo $i; ?> </td>
<td><?php echo $row1['book_name']; ?> </td>
<?php } ?>
</tr>
<?php
}
?>
</tbody>
<?php } ?>
</table>
My friends insisted me that the above method is a old one, and there is something to do with just few line codes. Is it?
If yes, could someone redefine my code and give me.
Thanks,
Kimz
Сan this be so?
$mysql_query1 = "select * from authors"
$result = mysql_query ( "select * from books where a_id=".$row['a_id']) or die ( mysql_error () );
The PHP method would be something like:
//First let's get all the values we need and store them in array format
// so that we don't need to make expensive calls to the database
<?php
$result = mysql_query("SELECT author_name, book_name FROM books b, authors a WHERE b.a_id=a.a_id");
$arr = array();
while($row=mysql_fetch_assoc($query)){
//storing books by author
$arr[$row['author_name']][]=$row['book_name'];
}
//so now we have an array like ['A1'=>'ABC','DEF'],['A2'=>'GHI']
?>
<table cellpadding="0" cellspacing="0" border="0">
<thead>
<tr>
<th>S.No</th>
<th>Book Name</th>
</tr>
</thead>
<tbody>
<?php
//let's print out the contents of our array in table format
foreach($arr as $author=>$val){
echo "<tr>
<td style='background:none;'><u>".$author."</u></td>
<td></td>
</tr>";
foreach($val as $ind=>$book_name)
{
echo "<tr>
<td>".$ind."</td>
<td>".$book_name."</td>
</tr>";
}
}
?>
</tbody>
</table>
Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Display List of Books filtered by dropdownlist php

Well i guess this must be a really dump question, but it's just that i 've been trying but with no results.
I have a webpage in which a display a list of books from my database, which works just fine. But now i'd like to add a dropdownlist so the customer will be able to filter books by category.
How can i acchieve this?.
I have this image so it may help you. Thanks in advance for your answwers!
<?php
require_once("../../seguridad/secure_user.php");
include("conexion.php");
$query = mysql_query("select * from libro order by id_libro desc");
?>
<div class="table-responsive">
<table class="table table-hover">
<thead bgcolor="3286CE">
<th><font color="#ffffff">Titulo
<th><font color="#ffffff">Categoria
<th><font color="#ffffff">Descripcion
<th>
</thead>
<?php
while ($datos = mysql_fetch_row($query)) {
?>
<tr>
<td><?php echo $datos[3]?>
<td><?php echo $datos[5]?>
<td><?php echo $datos[2]?>
<td><?php echo $datos[4]?>
<?php
}
?>
</table>
</div>
?>
1) upgrade your code mysql is depreciated and you should be using PDO or mysqli
2) Your query would need to be modified to allow the category to be changed in the WHERE clause.
$query = mysql_query("select * from libro order by id_libro desc WHERE category = $category");
You would restructure your code to allow these changes to take place, without knowing your table names we cannot restructure this for you.

How to address every line of a mysql table?

To create a dynamic table within php, I set the variable $count from a query, which counts the rows in specific table. Then I would like to create a table with the exact number of rows as a html table:
for($i=1;$i=<$count;$i++){
echo"<tr><td>$name</td><td>$rights</td></tr>";
}
That's the way i want the table to be displayed. But everytime the for-loop is called, the values of $name and $rights should be taken from the database-table. But how should i handle this? I thought about a simple query selecting the name from the line where ID equals i. But then i remembered that always when i delete an entry from the table there will be gaps.
For example when there 3 entries and i delete the second one. There just are 2 entries; so the name of the second row, which ID is 3, will never be selected. Is there any way of handling this problem in an appropriated way?
You wouldnt use a for you would use a while or a foreach with the results from the query.
<?php
$db = new PDO($dsn, $user, $pass);
$stmt = $db->query('SELECT id, rights FROM the_table');
?>
<table>
<thead>
<tr>
<th>Id</th>
<th>Rights</th>
</tr>
</thead>
<tbody>
<?php if($stmt !== false): ?>
<?php foreach( $stmt as $row): ?>
<tr>
<td><?php echo $row['id'] ?></td>
<td><?php echo $row['rights'] ?></td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>

Put records next to eachother in columns using mysql_fetch_array?

I use mysql_fetch_array to fetch data from a mysql results set:
while($row = mysql_fetch_array($qry_result)){
Next I would like to place the data into columns in a table, but maximum of two columns at each row.
So using a table:
<table>
<tr>
<td>Record Here</td>
<td>Record Here</td>
</tr>
<tr>
<td>Record Here</td>
<td>Record Here</td>
</tr>
<tr>
<td colspan="2">Record Here</td>
</tr>
As you see above, I want to loop the results and create table columns in the loop.
This so that the records line up two and two on a results page.
Remember, if there is an odd number of records, then the last table column would need a colspan of 2, or perhaps just use an empty column?
Anybody know how to do this?
If I use a for loop inside the while loop, I would just be lining up the same records x times for each while loop. Confusing...
Any ideas?
Thanks
Implement a (1-indexed) counter within the while loop. Then add (after the loop):
if ($counter%2)
echo '<td></td>';
This will leave an additional blank cell in your table if the last column contains only one row.
Something like this should work...
<table>
<?php
while(true) {
$row1 = mysql_fetch_array($qry_result);
if($row1 === false) break;
$row2 = mysql_fetch_array($qry_result);
if($row2 !== false) {
echo "<tr><td>$row1</td><td>$row2</td></tr>";
} else {
echo "<tr><td coslspan=\"2\">$row1</td></tr>";
break; // output the final row and then stop looping
}
}
?>
</table>
<table>
<tr>
<?
$i=1;
$num = mysql_num_rows($qry_result);
while($row = mysql_fetch_array($qry_result)){
if($i%2==1)
?>
<tr>
<?
?>
<td <? if($i==$num && $i%2==1)echo 'colspan="2"';?>><?=$row['keyName']?></td>
<?
if($i%2==0)
{
<?
</tr>
?>
}
$i++;
}
?>

Categories