LEFT JOIN with SUM not working - php

hoping I could get a hand with a LEFT JOIN + SUM issue I'm having.
The background: I'm building a wee finance system and want to calculate the value of all invoices within a given month (blank months = null). I have two tables:
tsm_finance_calendar - Containing 'months'.
tsm_finance_invoices - Contains details of each invoice.
My query:
<?php
$query = "SELECT tsm_finance_calendar.month,
SUM(tsm_finance_invoices.totalBilled)
FROM tsm_finance_calendar
LEFT JOIN tsm_finance_invoices
ON tsm_finance_calendar.month = tsm_finance_invoices.month
GROUP BY tsm_finance_calendar.month
ORDER BY 'id'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['month']. " - $". $row['SUM(totalBilled'];
echo "<br />";
}
?>
Output is on the right track (Month - $Blank) but lacks the result of the sum.
Any help gets a giant high-five :)
Thanks,
RR

Use the as keyword in query
$query = "SELECT tsm_finance_calendar.month, SUM(tsm_finance_invoices.totalBilled) as sum FROM tsm_finance_calendar LEFT JOIN tsm_finance_invoices ON tsm_finance_calendar.month = tsm_finance_invoices.month GROUP BY tsm_finance_calendar.month ORDER BY 'id'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['month']. " - $". $row['sum'];
echo "<br />";
}

$row["month"]-$row["SUM(totalBilled)"]
and you forgot to close a paren ^

Did u miss a closing parenthesis in 'SUM(totalBilled' there?
echo $row['month']. " - $". $row['SUM(totalBilled'];
And I wonder why you need a JOIN there if both the month field of tsm_finance_invoices is having similar values as tsm_finance_calendar.month ?

Related

Grabbing info from two different tables, assistance

I am trying to make a members page. For the rank it shows numbers so I made another table that has the rank id (1,2,3 etc) and added a name to it also.
Here is my code.
<?php
$getCoB = mysql_query("SELECT * FROM `members`
WHERE `CoB` = '1' && `user_state` = '1' ORDER BY `id`");
$id = ($getCoB['rank']);
$rankInfo = mysql_query("SELECT * FROM `ranks` WHERE `id` = '".$id."'");?>
<h2 class="title">Council of Balance members</h2>
<style>tr:nth-of-type(odd) { background-color:#F0F0F0;}</style>
<div style='padding:5px;'>
<?php
if(mysql_num_rows($getCoB) == 0)
{
echo "There are no Council of Balance members.";
} else {
echo "<table cellpadding=20 width=100%>";
while($row = mysql_fetch_assoc($getCoB))
{
echo "<tr><td style='background-color:transparent;'><b>". $row['name']
. "</b></td><td>Rank: ".$rankInfo['name']." <br/> Role: ". $row['role']."</td>";
}
echo "</table>";
}
?>
The problem is rankInfo['name'] is not showing up. I tried to do something on this line while($row = mysql_fetch_assoc($getCoB)) and tried to make it something like this while($row = mysql_fetch_assoc($getCoB)) || while($rank = mysql_fetch_assoc($rankInfo) and changed this part <td>Rank: ". $rankInfo['name'] . " to this <td>Rank: ". $rank['name'] . " but I end up with an error. If I leave it like it is, it just shows Rank: without the name I added into my database.
You can combine your two queries into one using an inner join.
<?php
$getCoB = mysql_query("SELECT m.name as member_name, m.role, r.name as rank_name
FROM `members` as m INNER JOIN `ranks` as r ON m.rank = r.id
WHERE `CoB` = '1' && `user_state` = '1' ORDER BY m.id");
?>
Because of how INNER JOIN works, this will only display members who have corresponding records in the ranks table. If there are some members that you want to display that have no rank record, use LEFT JOIN instead.
Then when you echo out the data, be sure to refer to the item you have fetched ($row) each time. In your code, you are referring to $rankInfo['name'], where $rankInfo is not a variable, but a mysql query from which no rows have been fetched.
while($row = mysql_fetch_assoc($getCoB)) {
echo "<tr><td style='background-color:transparent;'><b>". $row['member_name']
. "</b></td><td>Rank: ". $row['rank_name'] . " <br/> Role: " . $row['role'] . "</td>";
}

Printing table values in ascending order

I am trying to print out a users name and totalspent value in ascending order of totalspent. I.e, user that has spent the most will be outputed first then the next highest spender etc.
This is my current code, however, this only seems to output a single table row an infinite amount of times.
$query = "SELECT * FROM (
SELECT * FROM `members` ORDER BY `totalspent` DESC LIMIT 10) tmp order by tmp.totalspent asc";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
echo $row['name'] . " - $" . $row['totalspent'] . "<br/>";
}
select member_name, totalspent from tmp order by totalspent desc;
still can you show snippet of your table and snippet of answer you desire
The best way I can prefer for you to join two tables. The code should like follows-
$query = "SELECT * FROM temp.tmp, mem.members WHERE temp.totalspend = mem.totalspend ORDER by temp.totalspend ASC";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
echo $row['name'] . " - $" . $row['totalspent'] . "<br/>";
}
I believe, it will work for your smoothly... TQ

How can I perform these MySQL subqueries in a cleaner way?

Using legacy code which uses mysql instead of mysqli/pdo so don't worry about this, I'll update the queries for this later.
Even though my current method works, I'm positive there is a cleaner way of doing this rather than a query and 3 subqueries. I mainly want to learn how to better enhance my queries and minimizing the amount of them.
What I'm trying to do is
echo out all the data for each date with the date displayed on top
Display the count of entries for each user on that particular day next to the user
For each date, at the bottom of the above 2 bits of data, display the user/s with the highest number of entries
$query = mysql_query('SELECT * FROM entries GROUP BY DATE(dt)');
$g = 0;
while ($row = #mysql_fetch_array($query))
{
$group[$g] = date('y-m-d', strtotime($row['dt']));
echo $group[$g] . "<br />";
//display the person's name for today with their count
$dayquery = mysql_query('SELECT *, COUNT(username) as total FROM entries WHERE DATE(dt) = "'.$group[$g].'" GROUP BY username ORDER BY COUNT(username) DESC');
while ($today = #mysql_fetch_array($dayquery))
{
echo $today['first_name'] . " | " . $today['total'] . "<br />";
}
//display the highest count for today
$topquery = mysql_query('SELECT COUNT(username) as highest FROM entries WHERE DATE(dt) = "'.$group[$g].'" GROUP BY username ORDER BY COUNT(username) DESC LIMIT 1');
while ($toptoday = #mysql_fetch_array($topquery))
{
echo "Highest today: " . $toptoday['highest'] . "<br /><br />" ;
}
//display the users with the highest count for today
echo "Highest users: ";
$userstopquery = mysql_query('SELECT *, COUNT(username) as total FROM entries WHERE DATE(dt) = "'.$group[$g].'" AND COUNT(username) = "' . $toptoday['highest'] . '" AND GROUP BY username');
while ($topusers = #mysql_fetch_array($userstopquery))
{
echo $topusers['first_name'] . "<br />" ;
}
$g++;
}
The trouble I'm having is that when I try and reduce these subqueries and use MAX it will only output the highest count but not all the data for each date, which is what I need, including output of the user/s with the most amount of entries for that given day.
You could start with something like this. Note that I'm not using PHP's mysql_ API as it was deprecated 3 or 4 years ago...
require('path/to/mysqli/connection/stateme.nts');
$array = array();
$query = "
SELECT e.dt
, e.username
, COUNT(*) ttl
FROM entries e
GROUP
BY e.dt
, e.username
ORDER
BY e.dt, ttl DESC;
";
$result = mysqli_query($conn,$query);
while ($row = mysqli_fetch_assoc($result))
{
$array[] = $row;
}
print_r($array);

PHP Display MYSQL Results within a loop

I have a left join, code shown below that takes,
id
referrer
search term
client_id
From table 1 and then takes the following columns from table 2 using the left join query underneath.
client_id
visit_id
timedate
url1
$query = "SELECT table1.id, table1.search_term, table1.referrer, table1.client_id, table2.client_id, table2.url1, table2.visit_id, table2.timedate ".
"FROM table1 LEFT JOIN table2 "
"ON table1.id = table2.visit_id WHERE table1.ip_address = '$ip_address' AND table1.client_id='$client_id' Group BY visit_id, timedate";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){ ?>
<div id=''>
<?php "<br />";
echo $row['referrer']. " - ". $row['search_term'];
echo $row['timedate']. " - ". $row['url1']. " - ". $row['visit_id'];
echo "<br />"; ?>
</div>
<?php
}
What I am trying to do is format the rows so the referrer and search term only shows once and not on every line so that the results would look like this.
Referrer Search term
timedate url1 1
timedate Url1 1
timedate url1 1
referrer Search Term
timedate Url1 2
timedate Url1 2
timedate Url1 2
the numbers 1 and 2 are to represent different visit id's by which the results are grouped. At the moment i get the referrer and search term after every row because it is in the loop and understand that. Just don't know if i can show the referrer and searc term just once per group of results.
You have to save the current pending referrer-searchterm combination and check if it changes, if yes, print out the referrer-searchterm line:
$query = "SELECT table1.id, table1.search_term, table1.referrer, table1.client_id, table2.client_id, table2.url1, table2.visit_id, table2.timedate ".
"FROM table1 LEFT JOIN table2 "
"ON table1.id = table2.visit_id WHERE table1.ip_address = '$ip_address' AND table1.client_id='$client_id' Group BY visit_id, timedate" .
"ORDER BY referrer, search_term";
$result = mysql_query($query) or die(mysql_error());
$currentReferrerSeatchTerm = null;
while($row = mysql_fetch_array($result)){
$newReferrerSearchTerm = $row['referrer']. " - ". $row['search_term'];
echo '<div id=""><br>';
if($currentReferrerSeatchTerm != $newReferrerSearchTerm){
echo $newReferrerSearchTerm . '<br>';
$currentReferrerSeatchTerm = $newReferrerSearchTerm
}
echo $row['timedate']. " - ". $row['url1']. " - ". $row['visit_id'];
echo '<br></div>';
}
I usually set a var to store the referrer then check that on each loop through. If it's the same as the previous, do nothing. If it's different, display the new header info (referrer & search_term in your case) and then update the var.
$query = "SELECT table1.id, table1.search_term, table1.referrer, table1.client_id, table2.client_id, table2.url1, table2.visit_id, table2.timedate ".
"FROM table1 LEFT JOIN table2 "
"ON table1.id = table2.visit_id WHERE table1.ip_address = '$ip_address' AND table1.client_id='$client_id' Group BY visit_id, timedate";
$result = mysql_query($query) or die(mysql_error());
$prevRef = '';
while($row = mysql_fetch_array($result)){ ?>
<div id=''>
<?php "<br />";
if($prevRef != $row['referrer']) {
echo $row['referrer']. " - ". $row['search_term'];
$prevRef = $row['referrer'];
}
echo $row['timedate']. " - ". $row['url1']. " - ". $row['visit_id'];
echo "<br />"; ?>
</div>
<?php
}

mysql select by filter

Whats Wrong with my code its Returning 0
$query = "SELECT cid, COUNT(cid) FROM topic_reply WHERE cid='$forum_id'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo "There are ". $row['COUNT(cid)'] ." ". $row['cid'] ." items.";
echo "<br />";
}
I try all possible codes to display the results by its returng 0.. but if i remove the WHERE filter its returns all rows what happened? hehe
I'm not sure what you are trying to accomplish but I think it might be a count of a particular cid:
$query = "SELECT cid, COUNT(cid) FROM topic_reply WHERE cid='$forum_id' GROUP BY cid";

Categories