sum in query / subquery - php

Table has the following info:
date |vendor|sales|percent|
--------------------------
2009-03-03| 10 |13.50| 1.30 |
2009-03-10| 10 |42.50| 4.25 |
2009-03-03| 21 |23.50| 2.30 |
2009-03-10| 21 |32.50| 3.25 |
2009-03-03| 18 |53.50| 5.30 |
2009-03-10| 18 |44.50| 4.45 |
I want it to sort into separate tables depending on date as follows:
date |vendor|sales|percent|
--------------------------
2009-03-03| 10 |13.50| 1.30 |
2009-03-03| 18 |53.50| 5.30 |
2009-03-03| 21 |23.50| 2.30 |
date |vendor|sales|percent|
--------------------------
2009-03-10| 10 |42.50| 4.25 |
2009-03-10| 18 |44.50| 4.45 |
2009-03-10| 21 |32.50| 3.25 |
I can get this done but I cannot get it to give me the totals for each separate table like:
date |vendor|sales|percent|
--------------------------
2009-03-03| 10 |13.50| 1.30 |
2009-03-03| 18 |53.50| 5.30 |
2009-03-03| 21 |23.50| 2.30 |
Total Sales for 2009-03-03 = $90.50
Total percent for 2009-03-03 = $8.90
date |vendor|sales|percent|
--------------------------
2009-03-10| 10 |42.50| 4.25 |
2009-03-10| 18 |44.50| 4.45 |
2009-03-10| 21 |32.50| 3.25 |
Total Sales for 2009-03-03 = $119.50
Total percent for 2009-03-03 = $11.95
I can get the totals for all but not for individual tables.
Here is my code:
<?php
$con = mysql_connect("localhost", $dbUser, $dbPassword);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("beans", $con);
$result = mysql_query("SELECT * FROM Deposits WHERE market = '4' ORDER BY eventdate, vendor ASC") or die(mysql_error());
$dateChk = 0;
while($row = mysql_fetch_array($result))
{
$date = $row["eventdate"];
$liclass = $row["vendor"];
$url = $row["trxid"];
$amountdep = $row["amount"];
$depcheck = $row["checkno"];
$deposit_Total = $deposit_Total + $amountdep;
$deposit_3Total = $deposit_3Total + $depcheck;
$deposit_3 = $amountdep / 100;
$dep_percent = $deposit_3 * 3;
$depper_Total = $depper_Total + $dep_percent;
$week = date("W", db_date_to_timestamp($date));
$year = date("Y", db_date_to_timestamp($date));
If($dateChk != $week)
{
echo "<table class=\"adverts\" width=\%100\" cellpadding=\"4\">\n";
echo "<tr><th>Date</th><th>Vendor</th><th>Total Sales</th><th>3% Due</th><th>Week</th></tr>\n";
echo "<tr>";
echo "<td>$date</td>\n";
echo "<td>$liclass</td>\n";
echo "<td>$ $amountdep</td>\n";
echo "<td>$ $depcheck</td>\n";
echo "<td>$week</td>\n";
echo "</tr>";
}
else
{
echo "<tr>";
echo "<td>$date</td>\n";
echo "<td>$liclass</td>\n";
echo "<td>$ $amountdep</td>\n";
echo "<td>$ $depcheck</td>\n";
echo "<td>$week</td>\n";
echo "</tr>";
}
$dateChk = $week;
}
echo "</table>\n";
echo "<p><b>Total reported Market Sales are $ " . $deposit_Total . "</b></p>\n";
echo "<p><b>3 percent of Total reported Market Sales are $ " . $deposit_3Total . "</b></p>\n";
?>

(EDIT: sorry when I posted I saw that you need it in the query!)
$dateChk = 0;
$firstRow = 1;
while($row = mysql_fetch_array($result))
{
$date = $row["eventdate"];
$liclass = $row["vendor"];
$url = $row["trxid"];
$amountdep = $row["amount"];
$depcheck = $row["checkno"];
$deposit_Total = $deposit_Total + $amountdep;
$deposit_3Total = $deposit_3Total + $depcheck;
$deposit_3 = $amountdep / 100;
$dep_percent = $deposit_3 * 3;
$depper_Total = $depper_Total + $dep_percent;
$week = date("W", db_date_to_timestamp($date));
$year = date("Y", db_date_to_timestamp($date));
If($dateChk != $week)
{
if($firstRow == 0)
{
echo "</table>\n";
echo "<p><b>Total reported Market Sales are $ " . $deposit_week_Total . "</b></p>\n";
echo "<p><b>3 percent of Total reported Market Sales are $ " . $deposit_week_3Total . "</b></p>\n";
$deposit_week_Total = 0;
$deposit_week_3Total = 0;
}else
{
$firstRow = 0;
}
echo "<table class=\"adverts\" width=\%100\" cellpadding=\"4\">\n";
echo "<tr><th>Date</th><th>Vendor</th><th>Total Sales</th><th>3% Due</th><th>Week</th></tr>\n";
echo "<tr>";
echo "<td>$date</td>\n";
echo "<td>$liclass</td>\n";
echo "<td>$ $amountdep</td>\n";
echo "<td>$ $depcheck</td>\n";
echo "<td>$week</td>\n";
echo "</tr>";
}
else
{
echo "<tr>";
echo "<td>$date</td>\n";
echo "<td>$liclass</td>\n";
echo "<td>$ $amountdep</td>\n";
echo "<td>$ $depcheck</td>\n";
echo "<td>$week</td>\n";
echo "</tr>";
}
$dateChk = $week;
$deposit_week_Total = $deposit_week_Total + $amountdep;
$deposit_week_3Total = $deposit_week_3Total + $depcheck;
}
echo "</table>\n";
echo "<p><b>Total reported Market Sales are $ " . $deposit_Total . "</b></p>\n";
echo "<p><b>3 percent of Total reported Market Sales are $ " . $deposit_3Total . "</b></p>\n";
?>

SQL
"SELECT date, SUM(sales) FROM Deposits WHERE market = '4' GROUP BY date"
Istead of sum(sales) you have to use your own calculations. I suggest to put them into a model.

Would this help?
http://www.plus2net.com/sql_tutorial/sql_sum.php
SELECT SUM (sales) FROM `table_name` WHERE `date` = '$date_you_want'
From my below comment:
SELECT SUM (sales) FROM `table_name` WHERE `date` <= '$start_date_of_week' AND `date` >= '$end_date_of_week'
So basically WHERE date is less than and greater than the two dates that describe the start and stop of the week you want...
Or... I think you could also add the days to the value in the mysql
SELECT SUM (sales) FROM table_name WHERE date LIKE '$yyyy-mm-dd %' ...DATE_ADD code for adding days.. or INTERVAL.

You can get those sums straight by using GROUP BY WITH ROLLUP.

Related

Wordpress - Get All Rows In HTML Table

I have a custom wordpress table and am trying to get all rows in the db separated by year. My code now:
echo "<table width='100%'>";
for ($year = date("Y"); $year >= 2017; --$year) {
echo ("<tr><th>$year</th></tr>");
echo ("<tr><th>Champions</th>");
echo ("<th>Score</th>");
echo ("<th>Date</th></tr>");
global $wpdb;
$clubmatch = $wpdb->get_results("SELECT * FROM wp_club ORDER BY gamedate DESC");
foreach($clubmatch as $row){
echo "<tr><td>" . $row->names . "</td>";
echo "<td>" . $row->score . "</td>";
echo "<td>" . $row->gamedate . "</td></tr>";
}
echo ("<tr><td style='padding: 20px;'></td></tr>");
}
echo '</table>';
This gives me the following on screen:
2018
Champions Score Date
Sam Jones - Peggy Jones 81.43 2018-03-01
Joseph Parks - Carmen Parks 70.85 2017-12-17
2017
Champions Score Date
Sam Jones - Peggy Jones 81.43 2018-03-01
Joseph Parks - Carmen Parks 70.85 2017-12-17
How do I get it to show like this? Each row under the proper year?
2018
Champions Score Date
Sam Jones - Peggy Jones 81.43 2018-03-01
2017
Champions Score Date
Joseph Parks - Carmen Parks 70.85 2017-12-17
Thanks in advance!
Change the SQL query, so that it filters the result by the year of the field gamedate. So use this: (the code is indented for clarity)
$clubmatch = $wpdb->get_results(
"SELECT * FROM wp_club " .
"WHERE YEAR(gamedate) = '$year' " .
"ORDER BY gamedate DESC"
);
..instead of:
$clubmatch = $wpdb->get_results("SELECT * FROM wp_club ORDER BY gamedate DESC");

mysqli query to fetch row values without loop

I am newbie and need help to resolve my issue.
extract row values without loop.
Table:
----------------
YEAR | SALES
----------------
2011 | 45
2012 | 34
2013 | 23
2014 | 10
2015 | 48
----------------
PHP code:
$sql = "SELECT YEAR FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "YEAR: " . $row["YEAR"]. "<br>";
}
} else {
echo "0 results";
}
looking for solution to output the year value without loop , something similar below
while loop prints all row values , but would like to extract individual year value from query and assign it to a variable
$year1 = $row["YEAR"]
$year2 = $row["YEAR"]
$year3 = $row["YEAR"]
with your current code
$i=1;
while($row = $result->fetch_assoc()) {
${'year'.$i}= $row["YEAR"];
$i++;
//echo "YEAR: " . $row["YEAR"]. "<br>";
}
now you can access $year1; $year2 and so on

SELECT SUM data rank and Resource id #9 error PHP

I have a website in which logged in members are stored under a table called ‘users’
‘users’ table
users_sales_guild_id | users_first_name | users_surname
555 | Jane | Smith
333 | John | Smith
111 | Mike | Myers
The users have sales data in a 'sales_points' field which is in a separate table called ‘sales_list’.
‘sales_list’ table
sales_id | users_sales_guild_id | sales_points | sales_entry_date
1 | 555 | 50 | 2013-02-31 00:00:00
2 | 333 | 30 | 2013-02-31 00:00:00
3 | 111 | 10 | 2013-02-31 00:00:00
4 | 555 | 50 | 2013-03-31 00:00:00
5 | 333 | 30 | 2013-03-31 00:00:00
6 | 111 | 10 | 2013-03-31 00:00:00
Essentially what I am trying to do is a query which:
A. Calculates the total amount of 'sales_points' for each user from 'sales_list'
B. Lists 100 users with the user having the most points at the top, then ranking the next highest below and so on...
C. Im not after a ranking number, just the order itself.
With the code below I am getting 100 users printing ok, however I am getting a ‘Resource id #9’ message in the ’Total Points’ column when it prints. Can anyone help?
What I am trying to print
Jane Smith | 100
John Smith | 60
Mike Myers | 20
Code:
<?php
require_once ('config.inc.php');
$page_title = '';
include ('header.html');
if (!isset($_SESSION['users_id'])) {
$url = 'http://' . $_SERVER['HTTP_HOST']
. dirname($_SERVER['PHP_SELF']);
// Check for a trailing slash.
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
$url = substr ($url, 0, -1); // Chop off the slash.
}
// Add the page.
$url .= 'login.php';
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}?>
<h1>Rankings</h1>
<?php require_once ('database.php'); // Connect to the database.
$total = mysql_query("SELECT SUM(sales_points) FROM sales_list,users WHERE sales_list.users_sales_guild_id = users.users_sales_guild_id
AND sales_entry_date
BETWEEN '2013-10-01 00:00:00' AND '2013-11-30 23:59:59'
" );
$query = "SELECT us.users_id, us.dealership_id, us.users_sales_guild_id, us.users_first_name, us.users_surname, us.users_type,
de.dealership_id, de.users_dealer_name, de.class , de.region, de.state, de.users_dealer_code_id, de.users_dealer_code_new_id, de.users_model, de.pma
FROM users AS us, dealerships AS de
WHERE us.dealership_id = de.dealership_id
ORDER BY ’$total’ DESC
LIMIT 100";
$result = #mysql_query ($query);
// Table header.
echo '<table width="680"cellpadding="5" cellspacing="1" style="font-size:12px;">
<tr class="orangehead">
<td align="center"><b>Member</b></td>
<td align="center"><b>Title</b></td>
<td align="center"><b>Dealer</b></td>
<td align="center"><b>Category</a></b></td>
<td align="center"><b>Dealer Code</a></b></td>
<td align="center"><b>Total Points</a></b></td>
</tr>';
// Fetch and print all the records. echo '<td align="left"><strong>' . $row['sp_invoice_no'] . '</strong></td> ';
$bg = '#ffffff'; // Set the background color.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$bg = ($bg=='#eaeced' ? '#ffffff' : '#eaeced'); // Switch the background color. New: ' . $row['users_sales_guild_new_id'] . '
// $entries = floor($row['sp_entry_amount']/200);
echo '<tr bgcolor="' . $bg . '">';
echo '<td align="left"><strong>' . $row['users_first_name'] . ' ' . $row['users_surname'] . '</strong></td> ';
echo '<td align="center">' . $row['users_type'] . ' </td>';
echo '<td align="center"> ' . $row['users_dealer_name'] . ' </td>';
echo '<td align="center"> ' . $row['class'] . ' </td>';
echo '<td align="center"> ' . $row['users_sales_guild_id'] . ' </td>';
echo '<td align="center"> ' . $total . '</td>';
echo '</tr>
';
}
echo '</table>';
mysql_free_result ($result); // Free up the resources.
mysql_close(); // Close the database connection.
include ('footer.html'); // Include the HTML footer.
?>
You don't fetch you first result. Fetch it as an array (mysql_fetch_array()) for example.
// Execute query
$total_query = mysql_query("SELECT SUM(sales_points)
FROM sales_list, users
WHERE sales_list.users_sales_guild_id = users.users_sales_guild_id
AND sales_entry_date
BETWEEN '2013-10-01 00:00:00' AND '2013-11-30 23:59:59'");
// Fetch result
$total = mysql_fetch_array($total_query);
You echo this:
$total = mysql_query("SELECT SUM(sales_points) FROM sales_list,users WHERE sales_list.users_sales_guild_id = users.users_sales_guild_id
AND sales_entry_date
BETWEEN '2013-10-01 00:00:00' AND '2013-11-30 23:59:59'
" );
The variable $total contains the result of the query, which is a Resource. You should use mysql_fetch_assoc or a similar function to extract the result itself. It's best to give the SUM(sales_points) an alias, i.e. AS total_sales_points so you can fetch is easily.
By the way, the mysql_*-extension is soon-to-be deprecated. Good alternatives include MySQLi and PDO.
$query = mysql_query("SELECT SUM(sales_points) as points FROM sales_list,users WHERE sales_list.users_sales_guild_id = users.users_sales_guild_id
AND sales_entry_date
BETWEEN '2013-10-01 00:00:00' AND '2013-11-30 23:59:59'
" );
$row = mysql_fetch_object($query);
$total = $row->points;
You are echoing the mysql resource, you first need to fetch the results, then you can echo them.

Break and continue in a while loop

Problem
Basically I have got a game where 2 teams are competing with each other. With first while loop I get those team names and information. In the second loop I am fetching username/members who are participating in those teams and then run a query to fetch their records.
The final while loop I have used to Some up the teams calculation, i.e. if Team A have 2 players named as Joe and Mike and Team B have 3 players named as John,Jack and Dave So for Team A Joe did ran 5 km and Mike ran 7 km which brings up to a total of 12 km for team A. Likewise for team B John ran 11km, Jack did 2 km and Dave did 1km which makes a total of 14km for team B. But because of this loop is shows Team A = 12km and Team B = 26km. It will be great if anyone can guide me through to where I might be going wrong.
Code
$t_name = "Joe Running8 Vs Mike Running2";
$sql_team = 'SELECT * FROM teams WHERE t_name="'.$t_name.'" AND game_type = "Activity"';
$result_team = mysql_query($sql_team) or die(mysql_error());
$totalNoUsers = '';
$activityTotal = '';
$avgPP = '';
//Table structure for displaying the results
echo '<table border="1" align="center" width="100%">';
echo '<tr>';
echo '<th>Team Name</th>';
echo '<th>Total no Activity</th>';
echo '<th>Total Users</th>';
echo '<th>Avg per User</th>';
echo '<th>Avg %</th>';
echo '</tr>';
while($row_team = mysql_fetch_array($result_team)){
$sql_SelUsers = 'SELECT * FROM teams where t_name="'.$row_team['team'].'"';
echo $sql_SelUsers."<hr>";
$result_SelUsers = mysql_query($sql_SelUsers) or die(mysql_error());
$totalNoUsers = mysql_num_rows($result_SelUsers);
while($row_SU = mysql_fetch_array($result_SelUsers)){
//$accepted_on = "30/01/2013";
$userA = explode("/","27/01/2014");
$accepted_on = mktime(0,0,0, $userA[1],$userA[0],$userA[2]);
$date_time_compare = date('D, j M Y H:i:s', $accepted_on);
$sql = 'SELECT * FROM data_feeds where username="'.$row_SU['username'].'" AND gadget_data_type= "Activity" and gadget_name = "'.$row_SU['gadget_type'].'" and gadget_sub_data_type = "'.$row_SU['game_parameter'].'" and STR_TO_DATE( date_time, "%a, %e %b %Y %H:%i:%s" ) >= STR_TO_DATE( "'.$date_time_compare.'", "%a, %e %b %Y %H:%i:%s" ) ORDER BY df_id DESC';
$result_df = mysql_query($sql) or die(mysql_error());
echo $row_SU['username']."<br />";
/****** Here is the problem ********/
while($row_df = mysql_fetch_array($result_df)){
$activityTotal += $row_df['gadget_data_type_value'];
echo "<br /><strong>".$activityTotal."</strong><br />";
}
}//end while query data_feeds
echo "TnP-> ".$totalNoUsers;
$activityTotal = $activityTotal/1000;
$avgPP = ($activityTotal/$totalNoUsers);
echo '<tr>';
echo '<td>'.$row_team['challToTeam'].'</td>';
echo '<td>'.number_format($activityTotal, 2, '.', ',').'</td>';
echo '<td>'.$totalNoUsers.'</td>';
echo '<td>'.number_format($avgPP, 2, '.', ',').'</td>';
echo '<td>'.$totalNoUsers.'</td>';
echo '</tr>';
}//end while query Teams
echo '</table>';
You need to reset $activityTotal before your loop.
After the first loop its value is 12 km, and
then you add 14 km to it, which becomes 26km instead of 14 km .
Correction:
$activeTotal = 0 // RESET TO ZERO
while($row_df = mysql_fetch_array($result_df)){
$activityTotal += $row_df['gadget_data_type_value'];
echo "<br /><strong>".$activityTotal."</strong><br />";
}
$activityTotal set to empty or 0 before next team total start
//use
$activityTotal = 0; //init to 0 before loop

Echo variable once

How can i display variable only once in the table.
<?php
$sql = mysql_query("SELECT * FROM babydata");
while ($row = mysql_fetch_array($sql)) {
for ($i = 1; $i <= 72; $i++) {
if ($i == $weeknumber) {
echo "<tr><td width='40'>Week $i</td>";
echo "<td width='500' >" . count($row[$menucompare]) . "</td></tr>";
}
}
}
?>
this code display like this:
--------------
week4 | 1
-------------
week4 | 1
-------------
But i want to display weeknumber only once and count($row[$menucompare]) will be counted 2 in week 4 . not 1 and 1 .
Like this:
--------------
week4 | 2
---------------
Seems like you want to output the amount of tuples in babydata for a certain week. You can just filter out any tuples which dont belohnt to the $weeknumber in your query.
// TODO: Assert, that $weeknumber is an integer, to not be prune to SQL injection.
$weeknumber = (int)(($currentdate - $birthday) / (7 * 24 * 60 * 60)) + 1;
// Select the amount of tuples in babydata for the desired $weeknumber.
$result = mysql_query("SELECT count(*) FROM babydata ".
"WHERE week = $weeknumber");
// There is only one tuple with one column that contains the amount as number.
$row = mysql_fetch_row($result);
// Output the week and the amount of data.
echo "<tr><td width='40'>Week $weeknumber</td>" ;
echo "<td width='500' >".$row[0]."</td></tr>";
No need for loops.
To output all weeks and their respective amount of data:
// Select the amount of tuples in babydata for all weeks.
$result = mysql_query("SELECT week, count(*) FROM babydata ".
"GROUP BY week");
// For all weeks:
while ($row = mysql_fetch_row($result))
{
// Output the week and the amount of data.
echo "<tr><td width='40'>Week ".$row[0]."</td>" ;
echo "<td width='500' >".$row[1]."</td></tr>";
}
This assumes that you have a column week in your table babydata that contains just a number. This outputs only weeks, that have at least one tuple.
You can do that directly in the SQL. Warning: I didn't actually tested this.
SELECT week, count(week) FROM babydata GROUP BY week;
This will directly return a result like
--------------
week4 | 2
week5 | 3
--------------
Just replace week with the actual name of your week field, and adapt the PHP to handle the new result structure. Something along these lines:
$sql= mysql_query("SELECT * FROM babydata");
while($row = mysql_fetch_array($sql))
{
echo "<tr><td width='40'>Week ".$row[0]."</td>" ;
echo "<td width='500' >".$row[1]."</td></tr>";
}

Categories