I have a column name quantity, unit_price and total_amount. The total_amount field in my database set to zero, in my query I used SUM(unit_price*quantity) AS total_amount to get the total value as total_amount. But when I tried to get the sum of total amount as total_sum is always get 0. if is it because the total_amount field in my database is set to zero? What I want to do is get the SUM(total_amount) AS total_sum but it always displays 0.
This is my Query.
<?php
$mysqli = new mysqli("localhost", "root", "", "app");
$term = $_GET['supp'];
$result = $mysqli->query("SELECT *, SUM(unit_cost*quantity) AS total_amount FROM procurement WHERE supplier LIKE '%".$term."%' GROUP BY counter");
echo'<table id="tfhover" cellspacing="0" class="tablesorter" style="text-transform:uppercase;" border="1px">
<thead>
<tr>
<th>SUPPLIER</th>
<th>ITEM</th>
<th>DESCRIPTION</th>
<th>QTY</th>
<th>UNIT</th>
<th>UNIT PRICE</th>
<th>Total Amount</th>
</tr>
</thead>';
echo'<tbody>';
while($row = $result->fetch_assoc()){
echo'<tr>
<td>'.$row['supplier'].'</td>
<td>'.$row['item_name'].'</td>
<td>'.$row['item_description'].'</td>
<td>'.$row['quantity'].'</td>
<td>'.$row['unit'].'</td>
<td>'.number_format($row['unit_cost'], 2, '.', ',').'</td>
<td>'.number_format($row['total_amount'], 2, '.', ',').'</td>
</tr>';
}
echo'<TR> <TD COLSPAN=6 BGCOLOR="#99CCFF">TOTAL AMOUNT</TD> <td>'.number_format($row['total_sum'], 2, '.', ',').'</td></TR>';
echo "</tbody></table>";
?>
My another problem is when I insert this code echo' TOTAL AMOUNT '.number_format($row['total_sum'], 2, '.', ',').''; inside the while loop. I want to have just 1 total amount row.
SELECT *, SUM(unit_cost*quantity) AS total_amount FROM procurement WHERE supplier LIKE '%".$term."%' GROUP BY counter"
This is a select statement which would not update any data in the database.
It seems that your total_amount, which can be evaluated every time when you need it, is not necessarily exists as a column in your table.
Also, can you post your table structure ? Actually the SQL seems not correct anyway.
Related
I have a table that consist of records and i want to retrieve rows with minimum price. I try the code below, and i am only able to retrieve only one rows. i need to return all rows with minimum price for the same partno.
<tr>
<th>S/N</th>
<th>Part Number</th>
<th>Description </th>
<th nowrap="nowrap">Recommended Price</th>
<th nowrap="nowrap">Recommended Supplier</th>
</tr>
<?php
$get = mysqli_query($con,"SELECT MIN(price)As price,partno,supplier,description FROM tab_stockqty2 ");
$c=0;
while($rw = mysqli_fetch_array($get)){
$c++;?>
<tr>
<td nowrap="nowrap"><?php echo $c;?></td>
<td nowrap="nowrap"><?php echo $rw['partno'];?></td>
<td nowrap="nowrap"><?php echo $rw['description'];?></td>
<td><?php echo number_format($rw['price'],2);?></td>
<td><?php echo $rw['supplier'];?></td>
</tr>
<?php };?>
See Database Record:
It show return two rows, but it is only retuning only one row for the first set of partno-2070081
To retrieve all records with minimal price, per partno, the query should be something like this:
SELECT s.price,s.partno,s.supplier,s.description FROM tab_stockqty2 s
INNER JOIN (
SELECT MIN(price) as m, partno FROM tab_stockqty2 GROUP BY 2
) m on s.price = m.m and s.partno = m.partno
Demo: http://sqlfiddle.com/#!9/3e089/1
try this ==>
SELECT MIN(price)As price,partno,supplier,description FROM tab_stockqty2 group by partno
The SQL MIN returns only 1 row which is the most minimum.
What you can do is fetch all records and sort them on price based on ascending order.
SELECT price,partno,supplier,description FROM tab_stockqty2 ORDER BY price ASC;
Try this instead.
In this way you will get records based on price from Low to High.
I have a SQL query that returns all fields in a table:
$registro = mysqli_query($con,
"SELECT * FROM agenda ORDER BY procedimento LIMIT $limit, $nroLotes");
My question is, if possible, through this query, sum the particular column values associated with another column of values, eg
Among other columns there are "Column: Name" where the values are names and "Column: Value" where the values are numbers. The idea is to add up the values associated with the names.
I suppose I do a foreach inside the while, but I have difficulty in this approach.
The following piece code in question:
<?php
//...
$registro = mysqli_query($con, "SELECT * FROM agenda ORDER BY procedimento LIMIT $limit, $nroLotes");
$tabela = $tabela.'<table class="table table-striped table-condensed table- hover">
<tr>
<th width="300">Nome</th>
<th width="200">Procedimentos</th>
<th width="150">Valor Cobrado do serviço</th>
<th width="150">Valor Total dos serviços</th>
<th width="150">Porcentagem do Valor Total dos serviços</th>
<th width="150">Data</th>
</tr>';
while($linha = mysqli_fetch_array($registro)){
$porcentagem = ($linha['valor'] * 30) / 100;
$tabela = $tabela.'<tr>
<td>'.$linha['nome_funcionario'].'</td>
<td>'.$linha['procedimento'].'</td>
<td>'.number_format($linha['valor'], 2, ',', '.').'</td>
<td>'.number_format($porcentagem).'</td>
<!--cell containing the sum-->
<!--<td>'.number_format($sum).'</td>-->
<td>'.fechaNormal($linha['start']).'</td>';
}
$tabela = $tabela.'</table>';
$array = array(0 => $tabela,
1 => $lista);
echo json_encode($array);
?>
I enjoy some light ;)
Hi I've managed to sort a table by column when each is clicked.
This is my table:
<table class="table table-hover">
<thead>
<tr>
<th>Game ID </th>
<th>Game title </th>
<th>Developers </th>
<th>Year of release </th>
<th>No. of items in stock </th>
<th>Cost price </th>
<th>Options</th>
</tr>
</thead>
I then use this to order the table according to the column selected.
if (isset($_GET['sort'])){
$sort = $_GET['sort'];
$query = "SELECT * FROM Games ORDER BY " . $sort . ";";
$result = mysqli_query($connection, $query);
(Underneath this code I use a loop to insert data into the table)
All works perfectly apart from my 'Year of release' column, when I click this the table empties.
I have no idea why this is happening.
Release is a reserved term. You need to encapsulate it in backticks; or change your column name. This approach you are taking also opens you to SQL injections.
I'd add make a white list of terms $_GET['sort'] could be and compare that against $_GET['sort']. Rough untested code example:
$valid_columns = array('id', 'title', 'release', 'developer', 'stock', 'price');
if (in_array($_GET['sort'], $valid_columns)) {
$sort = $_GET['sort'];
$query = "SELECT * FROM Games ORDER BY `" . $sort . "`;";
//execute query and valid stuff
} else {
echo 'invalid column supplied
}
This way you know what is going to end up in your SQL; otherwise a user could add anything which may cause errors on hang up your application.
This is again an extended quetion of THIS.
I changed my table format, i mean i have created a separate table for vendor_locations where i store multiple locations against that vendor id in multiple rows. and also created a table vendor_products to store multiple products for that vendor.
Now my problem is, As both products and locations will be multiple for each vendor while displaying i am not getting how to display it in a single row.
if the products are 3 and location is 2 then, all the details will be displayed thrice. if i remove either location or product it will work properly. But how can i do this for both
if(isset($_POST['submit']))
{
$sql="SELECT vendor.id AS venid
, vendor.name AS VNAME
, vendor.category
, vendor.website
, vendor.email
, vendor.phone
, vendor.vat
, vendor.pan
, items.name AS iname
, location.name AS locname
, items.item_id
FROM vendor
INNER JOIN vendor_location ON vendor.id = vendor_location.vendor_id
INNER JOIN vendor_products ON vendor.id=vendor_products.vendor_id
INNER JOIN location ON vendor_location.location = location.loc_id
INNER JOIN items ON vendor_products.item_id=items.item_id
ORDER BY vendor.id";
}
$sql1 = mysql_query($sql) or die(mysql_error());
}
?>
<div class="w-box w-box-blue">
<div class="w-box-header">
<h4>Vendor</h4>
</div>
<div class="w-box-content">
<table id="dt_hScroll" class="table table-striped">
<thead><tr>
<th>Vendor ID</th>
<th>Vendor</th>
<th>Category</th>
<th>Website</th>
<th>Email</th>
<th>Phone</th>
<th>VAT</th>
<th>PAN</th>
<th>Products</th>
<th>Locations</th>
</tr>
</thead>
<tbody>
<?php
$current = ''; // STORE THE SUPPLIER SID
while($row = mysql_fetch_array($sql1)) {
if ($row['venid'] != $current) {
echo "<tr>
<td><a href='edit_vendor_details.php?id=$row[venid]'>{$row['venid']}</a></td>
<td>{$row['VNAME']}</td>
<td>{$row['category']}</td>
<td>{$row['website']}</td>
<td>{$row['email']}</td>
<td>{$row['phone']}</td>
<td>{$row['vat']}</td>
<td>{$row['pan']}</td>
";
$current = $row['venid']; // RESET STORED SID
}
else {
echo "<tr><td colspan='8'> </td>";
}
echo "<td>{$row['iname']}</td>";
echo "<td>{$row['locname']}</td>";
echo "</tr>";
}
echo('</tbody></table>');
?>
</tbody></table>
use group_concat on the fields if you only wish to show. like this:
SELECT vendor.id AS venid --rest of selection
, GROUP_CONCAT(location.name) AS locname
, GROUP_CONCAT(items.item_id)
FROM vendor --rest of your joins
GROUP BY vendor.id
see more about it here: MySQL Aggregate Functions
Below is my Query:
$query = "
SELECT *
FROM Teacher t
INNER JOIN Session s ON t.TeacherId = s.TeacherId
JOIN Grade_Report gr ON s.SessionId = gr.SessionId
WHERE
('".mysql_real_escape_string($sessionid)."' = '' OR gr.SessionId = '".mysql_real_escape_string($sessionid)."') ";
The results are stored in a table which code looks like this:
<table border='1'>
<tr>
<th>Session ID</th>
<th>Student Username</th>
<th>Student Name</th>
<th>Mark</th>
<th>Grade</th>
</tr>
<?php
while ($row = mysql_fetch_array($result)) {
echo "
<tr>
<td>{$row['SessionId']}</td>
<td>{$row['StudentUsername']}</td>
<td>{$row['StudentForename']} {$row['StudentSurname']}</td>
<td>{$row['Mark']}</td>
<td>{$row['Grade']}</td>
</tr>";
}
This query outputs 13 rows in the results which is fine when it selects all rows.
Now what happens is that I want the average mark for each session. So I include 'AVG(gr.Mark) as AvgMark' in the query and include <td>{$row['AvgMark']}</td> in the table. The Calculation it outputs is correct The problem is that the query now only outputs 1 row which is the top row of the query result. I understand this as AVG(gr.Mark) only requires one row when outputted.
So my question is that except using SELECT'AVG(gr.Mark) as AvgMark' in the query to find average marks of each session, is there a way I can workout average of each mark outside the query by using php so that the query output shows the 13 rows and is not affected and I can store the calculation of the average below the table rather than in the table?
The reason AVG returns one row is that it's an aggregate function, and without a GROUP BY clause operates on all rows.
Averages in PHP are just like averages everywhere else; total your values and divide by the number of samples. Hence, you can easily calculate the average in code by changing the code to:
<?php
$total = 0;
$count = 0;
while ($row = mysql_fetch_array($result)) {
$count++;
$total += $row['Mark'];
echo "
<tr>
<td>{$row['SessionId']}</td>
<td>{$row['StudentUsername']}</td>
<td>{$row['StudentForename']} {$row['StudentSurname']}</td>
<td>{$row['Mark']}</td>
<td>{$row['Grade']}</td>
</tr>";
}
$average = (int)($total/$count);
echo "<tr><td colspan=3></td><td>Average</td><td>$average</td></tr>".