php code to select sum and count of column - php

there are multiple column in my table ..
col1 col2 col3 price
500 700 100 10
501 700 100 20
502 700 100 30
503 700 100 10
4 70
I need to get count of col1 and display its sum.
and also display sum of price column...
But the main thing is i need to display this in last row....after all data...how can select this and echo in last row...
plz help me...
I need to echo exactly as i put the data in above table...
I need sql query and also need help to echo only sum of this two column in last row only......
SELECT *,IFNULL(col1,'SUM'), count(*) as count FROM coupon_entry WHERE Group By col1 WITH ROLLUP
<?php if (is_array($data)) { foreach($data as $row){ ?>
<tr>
<td><?php echo htmlspecialchars($row['col1']); ?></td>
<td><?php echo htmlspecialchars($row['col2']); ?></td>
<td><?php echo htmlspecialchars($row['col3']); ?></td>
<td><?php echo htmlspecialchars($row['price']); ?></td>
</tr>
<?php } }?>

One solution is to calculate the sum in PHP with variables :
<?php if (is_array($data)) {
$totalCol1 = 0;
$totalPrice = 0;
foreach($data as $row){
$totalCol1 += $row['col1'];
$totalPrice += $row['price'];
?>
<tr>
<td><?php echo htmlspecialchars($row['col1']); ?></td>
<td><?php echo htmlspecialchars($row['col2']); ?></td>
<td><?php echo htmlspecialchars($row['col3']); ?></td>
<td><?php echo htmlspecialchars($row['price']); ?></td>
</tr>
<?php }
<tr>
<td><?php echo $totalCol1;?></td>
<td></td>
<td></td>
<td><?php echo $totalPrice;?></td>
</tr>
}?>

Either you have to do 2 separate queries or else you have to do your calculations in PHP - either one is fairly simple although the PHP solution will probably be slightly (negligibly?) faster.
double-query:
$r = query('SELECT *
FROM yada-yada');
while ($row = fetch($r)) {
echo "<td>$row[col1]</td>\n";
echo "<td>$row[col2]</td>\n";
echo "<td>$row[col3]</td>\n";
echo "<td>$row[price]</td>\n";
}
$r2 = query('SELECT COUNT(*) as cnt, sum(col1) as sum_col1,
sum(price) as sum_price
FROM yada-yada...');
if ($row = fetch($r2)) {
echo "<td>$row['cnt']</td><td>$row['sum_col1']</td>...$row['sum_price']...\n";
}
calculate in PHP:
$cnt = $sum_col1 = $sum_price = 0;
$r = query('SELECT *
FROM yada-yada');
while ($row = fetch($r)) {
echo "<td>$row[col1]</td>\n";
echo "<td>$row[col2]</td>\n";
echo "<td>$row[col3]</td>\n";
echo "<td>$row[price]</td>\n";
$cnt++;
$sum_col1 += $row['col1'];
$sum_price += $row['price'];
}
echo "<td>$cnt</td><td>$sum_col1</td>...$sum_price...\n";

Below is my sql query to get count and sum of column.
SELECT COUNT(coupon) As Total,SUM(Price) AS TotalPrice FROM coupon_entry
And put this in seprate row below table...
<?php
foreach($tot as $tota)
?>
<tr style="background-color:#33CCFF;">
<td colspan="2" style="text-align:right; font-weight:bold;">Total Coupon</td>
<td><?php echo $tota['Total'];?></td>
<td style="text-align:right; font-weight:bold;">Total Amount in Rs</td>
<td><?php echo $tota['TotalPrice'];?></td>
</tr>
<?php }?>

Related

Could not get sum of each row in a column in php mysql table

enter image description hereenter image description hereI have a database table having multiple cols and data in many rows. I want to get sum of all data of all the data in each row and place in a col 'Total'. However, Grand total is showing in each row and not the total of each row.
I am presenting the code as below
<?php
include 'config.php';
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$add=mysqli_query($con,"SELECT Col1, Col2, Col3, Col4,
sum(Col1 + Col2 + Col3 + Col4) AS Total, SUM(Col1), SUM(Col2),
SUM(Col3), SUM(Col4)
from DistrictData WHERE District = 'District1' ");
while($row=mysqli_fetch_array($add))
{
$Total = $row['Total'];
$SUM1=$row['SUM(Col1)'];
$SUM2=$row['SUM(Col2)'];
$SUM3=$row['SUM(Col3)'];
$SUM4=$row['SUM(Col4)'];
$Total2= $SUM1 + $SUM2+ $SUM3+ $SUM4 ;
}
}
$sql="SELECT * FROM DistrictData WHERE District = 'District1'"; $counter = 0;
$result = $con->query($sql);
?>
<body>
<table >
<tr>
<td>Sr No.</td>
<td>Deptt</td>
<td>Data Description</td>
<td>Unit</td>
<td>Year</td>
<td>Blocks in District</td>
</tr>
<tr>
<td>Total</td>
<td>Col1</td>
<td>Col2</td>
<td>Col3</td>
<td>Col4</td>
</tr>
<?php
while($rows = $result->fetch_assoc())
{
?>
<tr>
<td><?php echo ++$counter; ?></td>
<td><?php echo $rows['Data']; ?></td>
<td><?php echo $rows['Description']; ?></td>
<td><?php echo $rows['Unit']; ?></td>
<td><?php echo $rows['Year']; ?></td>
<td> <?php echo $Total ?></td>
<td><?php echo $rows['Col1']; ?></td>
<td><?php echo $rows['Col2']; ?></td>
<td><?php echo $rows['Col3']; ?></td>
<td><?php echo $rows['Col4']; ?></td>
</tr>
<?php
}
?>
<tr>
<td>Total:</td>
<td> <?php echo $Total2 ?></td>
<td> <?php echo $SUM1 ?></td>
<td> <?php echo $SUM2 ?></td>
<td> <?php echo $SUM3 ?></td>
<td> <?php echo $SUM4 ?></td>
</tr>
</table>
<?php
$con->close();
?>
Output of the code
Please suggest any changes in the code so that I could get the sum for each row in Total Column.
Thanks in advance
Use this query for row sum of column elements
SELECT Col1+Col2+Col3+Col4 as I_want_this_figure from DistrictData
Note that a normalised environment would typically look more like this...
sr_no district_block val
1 1 5
1 2 6
1 3 5
1 4 8
2 1 226
2 2 112
2 3 4
2 4 5
3 1 2
3 2 7
3 3 3
3 4 8
... where (sr_no,district_block) are components of a PRIMARY KEY
Use Allies after every Sum() as something.
You will get last result when you take away total from while loop.
do your first Query under 2nd Query and pass the ID as parameter.
while($row = mysqli_fetch_array($query)){
$total_query = mysqli_query($con,"SELECT Col1, Col2, Col3, Col4,
SUM(Col1 + Col2 + Col3 + Col4) as Total from DistrictData WHERE id='row[yourID]'");
$total_result = mysqli_fetch_array($total_query);
NOW you can populate your data here
}
Hope this will help you.

Mysqli Query not pulling all results? [duplicate]

This question already has answers here:
MySQLi query returns only one row
(3 answers)
Closed 5 years ago.
So I had some mysql code that I've begun to rewrite into mysqli and have run into a problem with the query, and that is when I execute it, I only receive one set of results instead of the several that I know it should be. This is the new code I am using and was wondering whether anyone had any ideas on where I'm going wrong?
code:
<?php
if ($result = $link->query("SELECT SUM(step_count.steps) as total, leagues.league_id, leagues.league_name
FROM step_count INNER JOIN logins on step_count.unique_id = logins.unique_id INNER JOIN leagues ON leagues.unique_id = logins.unique_id GROUP BY leagues.league_id, leagues.league_name ORDER BY `total`
DESC LIMIT 100 ", MYSQLI_USE_RESULT))
$rank = 1; {
$row = $result->fetch_assoc();
$result->close();
}
?>
<tr>
<td>
<?php echo $rank++; ?>
</td>
<td>
<?php echo $row['league_name']; ?>
</td>
<td>
<?php echo $row['total']; ?>
</td>
</tr>
</table>
<?php
mysqli_close($link);
?>
you have to use a while loop
while($row = $result->fetch_assoc()){ ?>
<tr>
<td><?php echo $rank++; ?></td>
<td><?php echo $row['league_name']; ?></td>
<td><?php echo $row['total']; ?></td>
</tr>
<?php } ?>
try like this.
while($row = $result->fetch_assoc()){ ?>
<tr>
<td><?php echo $rank++; ?></td>
<td><?php echo $row->league_name; ?></td>
<td><?php echo $row->total; ?></td>
</tr>
<?php } ?>
you have to put a loop there.
you can replace this code and it will work
while($row =$result->fetch_assoc()){
?>
<tr>
<td><?php echo $rank++; ?></td>
<td><?php echo $row['league_name']; ?></td>
<td><?php echo $row['total']; ?></td>
</tr>
<?php }
$result->close();
}
?>
Fetch assoc retrieves one row as an associative array.
So you must use a while loop to keep fetching the rows until there are no more. The first example clearly illustrates how. I modified your whole code so you can copy paste everything. Do read the example though.
<?php
$query = "SELECT SUM(step_count.steps) as total,
leagues.league_id, leagues.league_name
FROM step_count
INNER JOIN logins on
step_count.unique_id=logins.unique_id
INNER JOIN leagues ON
leagues.unique_id=logins.unique_id
GROUP BY leagues.league_id, leagues.league_name
ORDER BY `total` DESC LIMIT 100";
$rank = 1;
if ($result = $link->query($query, MYSQLI_USE_RESULT)) {
while($row =$result->fetch_assoc()){
?>
<tr>
<td><?php echo $rank++; ?></td>
<td><?php echo $row['league_name']; ?></td>
<td><?php echo $row['total']; ?></td>
</tr>
<?php
}?>
</table>
<?php
}
mysqli_close($link);

Calculate total amount of rows for specific date

I have this working.
$queryPR = "SELECT * FROM `raport` WHERE DATE(`timestamp`) = CURDATE() AND (lokacioni = 'PR')";
I need the total amount of rows calculated for specific date.
I need also to the SUM('pagesat') somehow but I have no idea how.
Find the whole code below.
I am trying to build something simple to show the income and outcome for 3 locations that we have.
<table class="responsive-table">
<thead>
<tr>
<th>Vetura</th>
<th>Targa</th>
<th>Dite</th>
<th>Pagesa</th>
<th>Cmimi Ditore</th>
<th>Vazhdim</th>
<th>Te Tjera</th>
<th>Shpenzime</th>
<th>Komente</th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * FROM `raport` WHERE DATE(`timestamp`) = CURDATE() AND (lokacioni = 'FR')";
$stmt = $DBcon->prepare( $query );
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
?>
<tr>
<td><?php echo $row['vetura']; ?></td>
<td><?php echo $row['targa']; ?></td>
<td><?php echo $row['dite']; ?></td>
<td><?php echo $row['pagesa']; ?>€</td>
<td><?php echo $row['cmimiditore']; ?>€</td>
<td><?php echo $row['vazhdim']; ?>€</td>
<td><?php echo $row['tetjera']; ?>€</td>
<td><?php echo $row['shpenzime']; ?>€</td>
<td><?php echo $row['koment']; ?></td>
</tr>
<?php
$pagesa = $row['pagesa'];
$tetjera = $row['tetjera'];
$vazhdime = $row['vazhdim'];
$shpenzime = $row['shpenzime'];
}?>
</tbody>
</table>
<?php
$totali = ($pagesa + $vazhdime + $tetjera);
$gtotal = ($totali - $shpenzime);
?>
<div class="card grey">
<hgroup class="totalDitorRaport">
<h2>Total</h2>
<h1><?php echo $gtotal; ?>€</h1>
</hgroup>
</div>
try this
get the sum of the row pagesa in the loop
$queryPR = "SELECT * FROM `raport` WHERE DATE(`timestamp`) = CURDATE() AND (lokacioni = 'PR')";
$stmt = $DBcon->prepare( $query );
$stmt->execute();
$sum = 0;
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
$sum += $row['pagesa'];
}
echo $sum;

Ordering by a selected column from database

I have the following table that is meant to show a win/loss record and to have rankings. I'm running into two issues with it though.
First issue is that my rank <td> is not progressing like I want it to. What I mean by that is for each record that is looped and output, I want it to be numbered for.
i.e.:
1
2
3, etc.
The second part I cannot figure out is I want the person with the highest win total to be ranked the highest. I also want losses to be configured into that. So if someone is 5-0, their rank will be higher than someone's that is 5-1.
Could someone point me in the right direction with these issues I am running into?
<h2>Division 1</h2>
<table>
<tr>
<th>Rank</th>
<th>Name</th>
<th>Wins</th>
<th>Losses</th>
</tr>
<?php
try {
//Prepare
if ($stmt = $con->prepare("SELECT * FROM team_rankings WHERE `division`=1")) {
$stmt->execute();
$stmt->bind_result($ranking_id, $ranking_user_id, $ranking_firstname, $ranking_username, $ranking_division, $ranking_wins, $ranking_losses);
//var_dump($stmt);
if (!$stmt) {
throw new Exception($con->error);
}
$stmt->store_result();
while ($row = $stmt->fetch()) {
?>
<tr>
<td>1</td>
<td><?php echo $ranking_firstname; ?></td>
<td><?php echo $ranking_wins; ?></td>
<td><?php echo $ranking_losses; ?></td>
</table>
<?php
}
} else {
echo "<p>There aren't any players in division 1 yet.</p>";
}
}
catch (Exception $e)
{
echo "Error: " . $e->getMessage();
}
?>
You need to use ORDER BY like this
Do this:
SELECT * FROM team_rankings WHERE `division`=1" ORDER BY Wins DESC, Losses
More: link
For your first question you </table> needs to be out of your php while loop. Also have a counter which you can increment and show the order.
$count = 0;
while ($row = $stmt->fetch()) {
?>
<tr>
<td><php echo $count; $count++; ?></td>
<td><?php echo $ranking_firstname; ?></td>
<td><?php echo $ranking_wins; ?></td>
<td><?php echo $ranking_losses; ?></td>
</tr>
<?php } ?>
</table>
Something better? Use foreach
The numbering issue can be resolved as such:
$i = 1;
while ($row = $stmt->fetch()) {
?>
<tr>
<td><?php echo $i ?></td>
<td><?php echo $ranking_firstname; ?></td>
<td><?php echo $ranking_wins; ?></td>
<td><?php echo $ranking_losses; ?></td>
</tr>
<?php
$i++;
}
This sets a variable $i to '1' (outside the loop), echos the variable as the number in your <td>, and increments the variable $i++ before the loop is closed.
Oh yeah, and don't close your <table> inside the loop. :)
Looks like you want to use the ORDER BY clause in your query. It can sort by a column directly or by some calculation. For example, you could do:
SELECT *
FROM team_rankings
WHERE division = 1
ORDER BY
(wins - losses) DESC,
wins DESC
This way 1-0 would be ranked higher than 6-6 but lower than 2-1. How appropriate this is is up to you to decide.

How to showing report that group by archieve with PHP & MySQL?

I want to recapitulate report that grouped by month. But the results of sum is incorrect. It's just sum data in one month and show in all rows.
<?php
$query = mysql_query("SELECT * FROM barang GROUP BY arsip");
$i = 1;
while ($data = mysql_fetch_assoc($query)) {
?>
<tr class="<?php if ($i % 2 == 0) { echo "odd"; } else { echo "even"; } ?>">
<td><?php echo $i; ?></td>
<td><?php echo $data['arsip']; ?></td>
<td><?php
$Masuk= mysql_query("SELECT SUM(barang_in) AS masuk FROM barang GROUP BY arsip");
if($Masuk){
$data = mysql_fetch_assoc($Masuk);
echo $data['masuk'];
}
?></td>
<td><?php
$keluar= mysql_query("SELECT SUM(bijih_out+htm_out+pth_out) AS keluar FROM barang GROUP BY arsip");
if($keluar){
$data = mysql_fetch_assoc($keluar);
echo $data['keluar'];
}?></td>
<td><?php
$efisiensi= mysql_query("SELECT SUM((bijih_out+htm_out+pth_out)-barang_in) AS efisiensi FROM barang GROUP BY arsip");
if($efisiensi){
$data = mysql_fetch_assoc($efisiensi);
echo $data['efisiensi'];
}
?></td>
<td><?php
$persen= mysql_query("SELECT SUM(barang_in/(bijih_out+htm_out+pth_out))*1 AS persen FROM barang GROUP BY arsip");
$simbol = "%";
if($persen){
$data = mysql_fetch_assoc($persen);
echo number_format($data['persen'],2); echo $simbol;
}
?></td>
<?php
$i++;
}
?>
so that's my code. what's wrong with that? There are some columns for displaying income items, outcome items, efficiency ( difference of outcome and income items ) and percent of efficiency.
finally I found out the right code. Thankyou for #RandomSeed who helps me. This is my final code and it works!
<?php
$query = mysql_query("SELECT arsip, SUM(barang_in) AS income, SUM(bijih_out+htm_out+pth_out) AS outcome, SUM((bijih_out+htm_out+pth_out
)-barang_in) AS efficiency, SUM((barang_in / ( bijih_out + htm_out + pth_out))*100) AS percent FROM barang GROUP BY arsip");
$i = 1;
while ($data = mysql_fetch_assoc($query)) {
?>
<tr class="<?php if ($i % 2 == 0) { echo "odd"; } else { echo "even"; } ?>">
<td><?php echo $i; ?></td>
<td><?php echo $data['arsip']; ?></td>
<td><?php echo $data['income']; ?></td>
<td><?php echo $data['outcome']; ?></td>
<td><?php echo $data['efficiency']; ?></td>
<td><?php $simbol = "%"; echo number_format($data['percent'],0); echo $simbol; ?></td>
<?php
$i++;
}
?>

Categories