total sum of a row - php

I have this query which gives me the transactions for a user, and the output is a table with the information. There is this row named basket_value which contains some numbers, and I need to get the sum of those numbers. Could you please help me?
$query3 = 'SELECT users.first_name,users.last_name,users.phone,
retailer.date, SUM(retailer.basket_value),
retailer.time,retailer.location,retailer.type_of_payment
FROM users ,retailer
WHERE users.user_id="'.$id_user.'"
AND users.user_id=retailer.user_id GROUP BY users.user_id';
$result3 = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result3)) {
echo "Total ". $row['user_id']. " = $". $row['SUM(basket_value)'];
echo "<br />";
}

I suppose that also your query have some problem and suppose that you have an id to retrieve users, I would do in that way
$query3 = 'SELECT users.user_id,users.first_name,users.last_name,
users.phone, retailer.date,
SUM(retailer.basket_value) as total_sum,
retailer.time,retailer.location,retailer.type_of_payment
FROM users ,retailer WHERE users.user_id="'.$id_user.'"
AND users.user_id=retailer.user_id
GROUP BY users.user_id,users.first_name,users.last_name,
users.phone, retailer.date,retailer.time,retailer.location,
retailer.type_of_payment '
$result = $mysqli->query($query3);
Now if you want the sum for each user:
while ($row = $result->fetch_row()) {
echo "Player: ".$row['user_id']." total: ".$row['total_sum'];
}
If you want the WHOLE GLOBAL sum, you have to way:
Modify your query in that way:
SELECT SUM(retailer.basket_value) as total_sum
FROM retailer
Sum into while loop like: $total += $row['total_sum'];

You're missing a GROUP BY on your query. You most likely want to add GROUP BY users.user_id

Try this query:
SELECT u.first_name, u.last_name, u.phone, SUM(r.basket_value) as total_sum
FROM users u
JOIN retailers r
ON u.user_id = r.user_id
WHERE u.user_id="'.$id_user.'"
GROUP BY u.user_id

You can omit all other columns in the select list and only have the sum() aggregate run on the set to avoid the GROUP BY clause.
$query3 = 'SELECT SUM(retailer.basket_value) as total_sum
FROM users ,retailer WHERE users.user_id="'.$id_user.'"
AND users.user_id=retailer.user_id';

Related

Unable to get the value from a query with WHERE Clause

I am trying to get the Total Sum of values from a table. Query works without WHERE Clause, but i need to get the total sum per user. Like user ABC has 100USD and user BDC has 200USD. Here is the code
$PWithdrawls = mysqli_query($con, "SELECT * FROM withdraw WHERE status='Pending'");
$S_NO = 0;
while ($row = mysqli_fetch_assoc($PWithdrawls)) {
$S_NO++;
$posted_by = mysqli_query($con,"SELECT * FROM users WHERE userId=".$row['seller_id']);
$user_ad = mysqli_fetch_assoc($posted_by);
$TotalOrders_Amount = mysqli_query($con, "SELECT SUM(amount) as total FROM orders WHERE userId=".$row['seller_id']);
$sum_amount = mysqli_fetch_assoc($TotalOrders_Amount);
$sum = $sum_amount['total'];
And here is my call
<td>$<?php echo $sum; ?></td>
Here is DB
Think you have error in your SQL Query:
SELECT SUM(amount) as total FROM orders WHERE userId=".$row['seller_id'] GROUP BY userId LIMIT 1
You need to use GROUP BY to get actual SUM. Also you can get all users with Total, there is no need to second query:
SELECT u.*, SUM(o.amount) AS total
FROM users u
LEFT JOIN orders o ON (o.userId = u.id)
GROUP BY u.userId
This should get you entire user row + total of their orders.
I found the issue. I was calling the wrong variable. userId was not in my table, it was seller_id. So correct query was
$TotalOrders_Amount = mysqli_query($con, "SELECT SUM(amount) as total FROM orders WHERE seller_id=".$row['seller_id']);
Thanks to everyone. I really appreciate.

PHP MYSQL - Combine Query From Another Variable

May I know if I can combine queries from different variable or is there any other way. I want to insert $query_1 to $query_2
Example:
$sql = "SELECT l_id from mlk";
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$l_id[] = $row["l_id"];
}
}
mysqli_free_result($result);
foreach($l_id as $row){
$query_1= "(select count(*) from staff s where s.l_id = $row) as mlk_$row,";
}
$query_2= "SELECT mlk.lokasi,
//insert $query_1 here
from mlk INNER JOIN staff WHERE staff.l_id=mlk.l_id GROUP BY mlk.lokasi";
$result = mysqli_query($conn, $sql);
mlk is a table that stores staff working location
$query_2 will display the Location Name and I also want to display the total number of staff on that particular location. eg, Kuala Lumpur, 10
Just include the counting in the 2nd query:
SELECT mlk.lokasi, count(*) as no_of_staff
from mlk
INNER JOIN staff on staff.l_id=mlk.l_id
GROUP BY mlk.lokasi
I also changed the implicit join into an explicit one by moving the join condition from the where clause to the on clause.
Use left join for this to show all the locations and then each location staff count.
SELECT mlk.lokasi, count(*) as no_of_staff
from mlk
LEFT JOIN staff on staff.l_id=mlk.l_id
GROUP BY mlk.lokasi order by mlk.lokasi ASC

Why is my sql count printing alphabetical text?

$users = mysql_query("SELECT *, COUNT(votes.id) FROM users INNER JOIN votes
ON users.id=votes.recipientuserid WHERE votes.datenumber >='2014' ");
while($user = mysql_fetch_array($users)){
$count = $user[COUNT(votes.id)];
}
In phpmyadmin the query count displays a number. The value of $count is not a number but the users.username value. Why?
One way to accomplish what you want is to modify your query by adding a field name to count so that you can access it as any other field in the results:
SELECT *, COUNT(votes.id) as nbvotes FROM users ...
And the from php once you have the results, you can access it this way
$row['nbvotes']
where $row is the variable containing the record returned from mysql. Do not forget the appostrophes.
Cheers
$users = mysql_query("SELECT COUNT(votes.id) as count FROM users INNER JOIN votes
ON users.id=votes.recipientuserid WHERE votes.datenumber >='2014' ");
while($user = mysql_fetch_array($users)){
$count = $user['count'];
}

How to reference another table with a consistent primary key across tables

I have two tables which both have a unique PID. I need to know how I should setup the primary/foreign keys so I can access fields from both tables in one SQL statement.
For example: With the following data structure i'd like to echo out the players name and photo but also echo out all their stats via PHP as well. I have successfully done this with just the player Stats, but I do not know how to get access to fields in another table.
Here is my database structure so far:
Players
-PID (Set as Primary Key)
-Name
-Height
-College
-Photo
Stats
-PID
-Touchdowns
-Receptions
Current PHP Code:
$query="
SELECT * FROM Stats
ORDER BY Stats.FantasyPoints DESC";
$res=mysql_query($query);
$num=mysql_numrows($res);
$i=0;
while($i< $num){
$Name = mysql_result($res, $i, "Name");
$FantasyPoints = mysql_result($res, $i, "FantasyPoints");
echo $Name . ': '. $FantasyPoints . "<br />";
$i++;
}
$sql = "
SELECT p.*, s.*
FROM Players AS p
LEFT JOIN Stats AS s ON p.PID = s.PID
ORDER BY s.FantasyPoints DESC
";
You could also use a JOIN rather than a LEFT JOIN which would limit the result to only players who have stats
Edited sql to produce result similar to your own sql.
======================================================
This is how I would go about it...
$query =
"
SELECT s.*, p.*
FROM Stats AS s
LEFT JOIN Players AS p ON p.PID = s.PID
ORDER BY s.FantasyPoints DESC
";
$res = mysql_query($query);
while ($row = mysql_fetch_assoc($res))
{
echo "{$row['name']}: {$row['FantasyPoints']}<br />";
}

How to send SQL count data & array data together?

I have a script designed to print out values of students who have accrued more than 3 tardies. I want this script to print out both the student name, and the amount of times they've been tardy, but so far I've been only able to print out their names with the following script:
$sql = "select DISTINCT StudentID,classid,date from attendance_main where status = 'Tardy' AND classid like '%ADV%'";
$result = mysql_query($sql) or die (mysql_error());
while($row=mysql_fetch_array($result)) {
$studentid = $row['StudentID'];
$sql2 = "select distinct StudentID,classid,date from attendance_main where StudentID = '$studentid' AND status = 'Tardy' AND classid like '%ADV%'";
$result2 = mysql_query($sql2) or die (mysql_error());
while($row2=mysql_fetch_array($result2)) {
$tardycount = mysql_num_rows($result2);
$studentid = $row2['StudentID'];
if($tardycount >= 3) {
$sql3 = "select * from students where rfid = '$studentid'";
$result3 = mysql_query($sql3) or die (mysql_error());
while($row3=mysql_fetch_array($result3)) {
$fname[] = $row3['fname'];
}
}
}
}
$newdata = array_unique($fname);
foreach ($newdata as $value) {
echo $value;
}
I can't think of how to intuitively do this. Keeping it all in the while loop didn't work (I had multiple results coming up for the same students despite requesting unique entries) so using array_unique was the only method I could think of.
Thanks for any help!
Something like this:
SELECT
attendance_main.StudentID,
students.fname,
COUNT(attendance_main.*) AS `times_tardy`
FROM
attendance_main
INNER JOIN
students
ON
attendance_main.StudentID = students.rfid
WHERE
attendance_main.status = 'Tardy'
AND
attendance_main.classid like '%ADV%'
GROUP BY
attendance_main.StudentID
HAVING
`times_tardy` > 3
Joining the two tables gets you the tardy count and student's name in one query, and the GROUP BY and HAVING clause that get you only the students with more than 3 tardy entries.
You can (and should) do almost everything in SQL. It should look something like this.
select StudentID, classid, date count(*)
from attendance_main
where status = 'Tardy' AND classid like '%ADV%'"
left join student on student.rfid = attendance_main.StudentId
group by StudentId
having count(*) > 3;
Here's how it works.
select the results you want to work with:
select StudentID, classid, date count(*)
from attendance_main
where status = 'Tardy' AND classid like '%ADV%'"
Join the students to your result set on the common id
left join student on student.rfid = attendance_main.StudentId
group everything by student. We use count(*) to get the number of items. We know we're only dealing with tardies because of the where clause in the select.
group by StudentId
limit the results to only tardies above 3 with the having claues (this is like a where clause for the group by)
having count(*) > 3;

Categories