I have 3 tables like this
Orders Table
orders `order_id`,`order_date`
Orders_items table
orders_items `order_id`,`product_id`,`quantity`,`parent`
Products table
products `product_id`,`product_price`
MY Expectation
I want to make grand total in last row and dynamically, I have built my own query and work to show data from multiple tables above, but cannot display grand total as I mentioned above.
This my query
<?php
$query = $db->prepare("SELECT * FROM orders WHERE month(order_date)='".$_POST['bulan']."' AND YEAR(order_date)='".$_POST['tahun']."'");
?>
<table class="table table-hover table-bordered display" id="report" width="100%">
<thead>
<tr>
<th>Tanggal</th>
<th>Customer</th>
<th>Quantity</th>
<th>Harga</th>
<th>Total Harga</th>
</tr>
</thead>
<tbody>
<?php
$query->execute();
$row = $query->rowcount();
if($row > 0){
while($data = $query->fetch(PDO::FETCH_ASSOC)){
$oID = $data['order_id'];
$item = $db->prepare("SELECT * FROM orders_items WHERE order_id = '$oID' AND parent=3");
$item->execute();
while($i = $item->fetch(PDO::FETCH_ASSOC)){
$pID = $i['product_id'];
$product = $db->prepare("SELECT * FROM products WHERE product_id = '$pID'");
$product->execute();
while($p = $product->fetch(PDO::FETCH_ASSOC)){
//fech data
echo "<tr>
<td>{$data['order_date']}</td>
<td>{$data['order_name']}</td>
<td>{$i['quantity']}</td>
<td>Rp. ".number_format($p['product_price'])."</td>
<td>Rp. ".number_format($p['product_price']*$i['quantity'])."</td>
</tr>";
}
}
$total = 0;
$oID = $data['order_id'];
$rinci = $db->prepare("SELECT orders_items.order_id, SUM(orders_items.quantity * products.product_price ) AS grand_total
FROM orders_items JOIN products ON products.product_id=orders_items.product_id WHERE order_id = '$oID'
GROUP BY order_id");
$rinci->execute();
foreach($rinci as $r){
$total += $r['grand_total'];
?>
<tr class="bg-primary text-white">
<td class="text-center"><strong>Total</strong></td>
<td></td>
<td></td>
<td></td>
<td><strong>Rp. <?=number_format($total);?></strong></td>
</tr>
My query shows several rows as total based on order_id, if I change my query and group by another column the total is disappear. Here is my result based on query above
Here's my table with several total rows
How to make sub total only show at the end of rows and summarize all total price * quantity?
Sorry for my English.
Big thanks for someone who gives me an answer and solve my problem.
Probably this will work
while($data = $query->fetch(PDO::FETCH_ASSOC)){
$oID = $data['order_id'];
$item = $db->prepare("SELECT order_items.*, products.*, (order_items.quantity*products.product_price) as total FROM order_items LEFT JOIN products ON products.product_id = order_items.product_id WHERE order_id='$oID' AND parent=3");
$item->execute();
while($i = $item->fetch(PDO::FETCH_ASSOC)){
?>
<tr>
<td><?php echo $data['order_date'];?></td>
<td><?php echo $data['order_name'];?></td>
<td><?php echo $i['quantity'];?></td>
<td>Rp. <?php echo number_format($i['product_price']);?></td>
<td>Rp. <?php echo number_format($i['product_price']*$i['quantity']);?></td>
</tr>
<?php
}
}
Related
Hey guys I have one mysql table tick where i have some info like user id now to display that data I need to retrieve from user table name of the user based on that id
?php
$mysql5 = mysqli_query($dbc, "SELECT * FROM tick where status='1' ORDER BY dt DESC LIMIT 6 ");
if($indtbl = mysqli_fetch_array($mysql5))
{
$title = $indtbl['tickettitle'];
$company = $indtbl['companyname'];
$companyid =$indtbl['compid'];
$trackid = $indtbl['trackid'];
$assignto = $indtbl['assignto'];
$priority = $indtbl['priority'];
}
?>
and user table query is based on first one
<?php
$findresults2323 = mysqli_query($dbc, "SELECT * FROM users WHERE id= '$assignto'");
if($rest = mysqli_fetch_array($findresults2323))
{
$userimg = $rest['img'];
$fname1 = $rest['fname'];
$lname1 = $rest['lname'];
}
?>
now the problem is when i am fetching the array
<thead>
<tr>
<th class="text-left">Title</th>
<th>Company</th>
<th>Ticket ID</th>
<th>Assign To</th>
<th>Priority</th>
</tr>
</thead>
<?php
while($rowten = mysqli_fetch_array($mysql5)) {
$retrive11 = mysqli_fetch_array($findresults23);
?>
<tr>
<td><a href="readit.php?id=<?php echo $rowten["id"];?>"><?php echo $rowten["tickettitle"]; ?></td>
<td><a href="readit.php?id=<?php echo $rowten["id"];?>"><?php echo $rowten["companyname"];?> <?php echo $rowten["compid"];?></td>
<td><a href="readit.php?id=<?php echo $rowten["id"];?>"><?php echo $rowten["trackid"]; ?></td>
<td><a href="readit.php?id=<?php echo $rowten["id"];?>"><?php echo $retrive11['fname'];?></td>
<td><a href="readit.php?id=<?php echo $rowten["id"];?>"><?php echo $rowten["priority"]; ?></td>
</tr>
<?php
}
?>
i am getting the error
Notice: Trying to access array offset on value of type null on line 459
line 459 is
<td><a href="readit.php?id=<?php echo $rowten["id"];?>"><?php echo $retrive11['fname'];?></td>
what I am doing wrong
In order to use 2 queries, you need to run the second query inside of the loop so it retrieves the specific user record for the given result from the tick query.
while($rowten = mysqli_fetch_array($mysql5)) {
$assignto = $rowten['assignto'];
$findresults2323 = mysqli_query($dbc, "SELECT * FROM users WHERE id= '$assignto'");
$retrive11 = mysqli_fetch_array($findresults23);
However, this is very inefficient as it requires a query on the user table for every result in the tick query. The proper way of doing this is to use a single query with a join.
SELECT tick.*, users.fname FROM tick LEFT JOIN users ON (tick.assignto=users.id) where tick.status='1' ORDER BY tick.dt DESC LIMIT 6
The result of this query will have all the data from both your queries in one result.
I have data like this:
ID
Parts Number
Parts Name
Std Qty
Stock
1
9810001
NGK-11O7GGH
12
10
1
9810010
NGK-1187GGH
12
10
2
3810001
OVH-78GH
14
16
2
4810010
OVH-86GS
14
16
So, each ID can have many parts variant, but user only set the stock for each ID not each variant.
Then, the table should be look like this:
Table with rowspan in excel
How i can dynamically make this table with PHP and MySQL?
So i can export to excel correctly.
My Code:
<?php
$pit = 10;
if($pit<=6){
$std = 'usix';
}elseif($pit>=7 || $pit<=10){
$std = 'sevten';
}if($pit>10){
$std = 'tenplus';
}
$inv = mysqli_query($conn, "SELECT i.*, s.$std AS std FROM inventory i, sparepart s WHERE id_dealer='1' AND s.id_parts=i.id_parts");
?>
<table class="table table-bordered">
<thead>
<th>No</th>
<th>Part Number</th>
<th>Deskripsi</th>
<th>Std Qty</th>
<th>Stock</th>
<th>Status</th>
</thead>
<tbody>
<?php
$i = 1;
while($d=mysqli_fetch_array($inv)){
$id = $d['id_parts'];
$varian = mysqli_query($conn, "SELECT * FROM varian WHERE id_parts='$id'");
$varian2 = mysqli_query($conn, "SELECT * FROM varian WHERE id_parts='$id'");
if($d['stock']>$d['std']){
$status = 'STOCK AMAN';
$class = 'text-success';
}elseif($d['stock']<$d['std']){
$status = 'STOCK LOW';
$class = 'text-danger';
}
echo "
<tr>
<td>$i</td>
<td style='padding:0'>";
while($x=mysqli_fetch_array($varian)){
echo "
<p class='mb-0 p-1'>$x[part_number]</p><hr>"
;
}
echo "</td><td style='padding:0'>";
while($y=mysqli_fetch_array($varian2)){
echo"
<p class='mb-0 p-1'>$y[nama_var]</p><hr>
";
}
echo
"</td>
<td>$d[std]</td>
<td>$d[stock]</td>
<td class='$class'>$status</td>
</tr>
";
$i++;
}
?>
</tbody>
</table>
I want to display the transaction records of some particular customers stored in MySQL table.
I tried the follwing:
<table>
<tr>
<th>Transaction ID</th>
<th>Customer ID</th>
<th>Description</th>
<th>Amount</th>
<th>Date</th>
</tr>
<?php
$stmt0 = $mysqli->prepare("SELECT id FROM customers WHERE status = ?");
$stmt0->bind_param('i',$status);
$stmt0->execute();
$stmt0->store_result();
$stmt0->bind_result($cust_id);
while ($stmt0->fetch())
{
$stmt = $mysqli->prepare("SELECT id,description,amount,date FROM transactions WHERE cust_id = ? ORDER BY id DESC");
$stmt->bind_param('i',$cust_id);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id,$description,$amount,$date);
while ($stmt->fetch())
{
?>
<tr>
<td><?php echo $id; ?></td>
<td><?php echo $cust_id; ?></td>
<td><?php echo $description; ?></td>
<td><?php echo $amount; ?></td>
<td><?php echo $date; ?></td>
</tr>
<?php
}
$stmt->close();
}
$stmt0->close();
?>
</table>
It displays transactions records of the particular customers as per my requirements, but it displays records by grouping by "cust_id". I need to display them by ordering "id" in Descending order.
Please help!
You can make use of SUB QUERIES and get the results in one SQL Statement itself.
Like -
<?php
$stmt0 = $mysqli->prepare("SELECT t.id,t.description,t.amount,t.date FROM transactions t WHERE t.cust_id = (SELECT id FROM customers WHERE status = ?) ORDER BY t.id DESC");
$stmt0->bind_param('i',$status);
$stmt0->execute();
$stmt0->store_result();
$stmt0->bind_result($id,$description,$amount,$date);
//PRINT/echo $id,$description,$amount,$date to the front end now
?>
This should return $id,$description,$amount,$date values in descending order of the $id.
Another way is using SQL JOINS (preferred over sub queries although internal execution will almost be the same)
$stmt0 = $mysqli->prepare("SELECT t.id,t.description,t.amount,t.date FROM transactions t INNER JOIN customers c on t.cust_id=c.id WHERE c.status = ? ORDER BY t.id DESC");
//rest of the code remains same
i just moved to asp and php and i'm able to connect to mssql database and retrieve records. what i'm currenlty finding it hard to do is how to do pagination through the records showing 10 records at a time.
<table width="40%" border="1" align="center" cellpadding="5" cellspacing="5">
<tr>
<td>Item-</td>
<td>Quantity</td>
<td>Price</td>
</tr>
<?php
while( $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC) ) {
?>
<tr>
<td> <?php echo $row['item'] ?></td>
<td><?php echo $row['quantity'] ?></td>
<td><?php echo $row['rprice'] ?></td>
</tr>
<?php
}
?>
<tr>
<td><div align="left">Previous</div></td>
<td> </td>
<td><div align="right">Next</div></td>
</tr>
</table>
PHP SCRIPT
<?php require_once('Connections/db.php'); ?>
<?php
$sql = "SELECT * FROM item_table order by item desc";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query( $conn, $sql , $params, $options );
$row_count = sqlsrv_num_rows( $stmt );
if ($row_count === false)
echo "Error in retrieveing row count.";
else
echo $row_count;
?>
You can use OFFSET to get specific results:
$startingRow = 5;
$rowsPerPage = 10;
SELECT * FROM item_table order by item desc
OFFSET $startingRow ROWS FETCH NEXT $rowsPerPage ROWS ONLY
You will get results from 5th to 15th
If you want to do the paging in SQL Server, you can use the ROW_NUMBER function to order your rows & specify a starting point in the WHERE clause, and number of records in the TOP clause.
See the examples below. I prefer the CTE syntax.
--inline syntax
select top(10) * from (select row_number() over(order by item) as rid, * from item_table) as d where rid>10;
--cte syntax
with _numberedData as
(
select
row_number() over(order by item) as rid,
*
from item_table
)
select top(10)
*
from _numberedData
where rid>10;
I've done something similar to this table below quite a few times, where I use a while statement to populate the <td> section of a table, but I've never done it before where part of the <td> is populated with a foreach statement, and it's confusing me.
In this example, I create a table, then I populate the first column with a list of suppliers, based on the number of tables inside of my database. (each supplier has its own table).
$supplierList = array();
$showTable = "SHOW TABLES from dbOne";
$getSuppliers = mysqli_query($con, $showTable);
while ($row = mysqli_fetch_row($getSuppliers)) {
$supplierList[] = $row;
}
$supplierList = array_reduce($supplierList, 'array_merge', array());
Now I have my array that contains the list of all my suppliers, and I use that to generate the <td>s in my table.
<table>
<thead>
<th style="text-align: center;">Supplier</th>
<th style="text-align: center;">Earliest line</th>
<th style="text-align: center;">Latest line</th>
<th style="text-align: center;"># of total lines</th>
</thead>
<?php
foreach ($supplierList as $subList) {
$supplierName = $subList;
$earlyExp = "SELECT date FROM $subList ORDER BY date DESC LIMIT 1" ;
$earlyExpQuery = mysqli_query($con, $earlyExp);
$lateExp = "SELECT date FROM $subList ORDER BY date ASC LIMIT 1" ;
$lateExpQuery = mysqli_query($con, $lateExp);
$countLines = "SELECT * from $subList";
$countLinesQuery = mysqli_query($con, $countLines);
$countLinesCount = mysqli_num_rows($countLinesQuery);
while ($row = mysqli_fetch_array($earlyExpQuery)) {
$earlyExpDate = $row['date'];
?>
<tbody>
<td><img src = "/img/suppliers/<?= $supplierName ?>.png"></td>
<td style="text-align: center;"><?= $earlyExpDate ?></td>
<td style="text-align: center;"><?= $lateExpDate ?></td>
<td style="text-align: center;"><?= $countLinesCount ?></td>
</tbody>
<?php
}
}
?>
</table>
The table itself builds correctly, and displays each supplier in a unique row. I cannot figure out though how to populate the other parts of the row with the information based off the unique supplier in the foreach statement.
Okay, I sorted this out. In case it helps anyone else, here's how I did it:
This code goes in the same spot as my post above - so in between the header and the body of the table. I did not need to use any <tr>.
<?php
foreach ($supplierList as $subList) {
$supplierName = $subList;
$earlyExp = "SELECT * FROM $subList where dateOne != '' UNION SELECT * from $subList where dateTwo != '' ORDER BY dateTwo, dateOne ASC LIMIT 1" ;
$earlyExpQuery = mysqli_query($con, $earlyExp);
$lateExp = "SELECT * FROM $subList where dateOne != '' UNION SELECT * from $subList where dateTwo != '' ORDER BY dateTwo, dateOne DESC LIMIT 1" ;
$lateExpQuery = mysqli_query($con, $lateExp);
$countLines = "SELECT * from $subList";
$countLinesQuery = mysqli_query($con, $countLines);
$countLinesCount = mysqli_num_rows($countLinesQuery);
while ($row = mysqli_fetch_array($earlyExpQuery)) {
$earlyExpDate = $row['dateTwo'] ? $row['dateTwo'] : $row['dateOne'];
}
while ($row = mysqli_fetch_array($lateExpQuery)) {
$lateExpDate = $row['dateTwo'] ? $row['dateTwo'] : $row['dateOne'];
?>
They key is that I had to close off each individual while statement except the last one - closing that after I closed the </tbody> tag but before the </table>, like so:
</tbody>
<?php
}
}
?>
</table>