How to get grand total of many tables' totals - php

I have 500 tables, all containing records of dollar amounts in the field "sales".
The following gets me the total sales of green items per table:
$tabletotal = mysql_query("SELECT sum(sales) FROM databasename.$tablename
WHERE type = 'green' AND descr LIKE '%SOLD%' ");
$row = mysql_fetch_assoc($tabletotal);
$answer= $row['sum(sales)'];
So if a particular table has 4 green items and they were sold for $4, $6, $7, and $3, then the answer I get above is $20.
Now, what I don't know how to do, is to get the total of all green items in ALL 500 tables. So if table 1 has a total of $20, table 2 a total of $36, table 3 a total of $15, and so on, I want to get the grand total in all tables together (in this case $71 but it would be more for 500 tables obviously).
Any help anyone?

Probably best to use a for loop:
$tables = array('tbl1', 'tbl2', 'tbl3', ..., 'tbl499');
$total = 0;
foreach ($tables as $t)
{
$tabletotal = mysql_query("SELECT sum(sales) tot FROM databasename.$t WHERE type = 'green' AND descr LIKE '%SOLD%'");
$row = mysql_fetch_assoc($tabletotal);
$total += $row['tot'];
}
Alternatively, you could generate a giant SQL query using UNIONs, but it's essentially the same thing.
As Dream Eater mentions; you shouldn't be in this situation in the first place.

Related

Count total Average rating with PHP

How would I go about running a PDO query and then processing the results with PHP to output an Average rating for a specific blank based on user inputted reviews?
Each review is weighted on 2 criterias, Service and Price. Both of this are 0-5 therefore the end average is weighted out of 10. Per review bases I currently use the following code to calculate the Average Rating for the specific review.
$rating_total = $row['review_service_rating'] + $row['review_price_rating'];
$average_rating = ($rating_total / 100) * 100;
So for each review there are 2 sql rows for review_service_rating and review_price_rating both of this are out of 5.
However I'm not exactly sure how to Count all of the ratings and then determine base grade for the specific page out of 10.
So let's say we have 3 reviews. This reviews are 7/10, 8/10 and 10/10. Logically we would add up all of the numbers and then add up all of /10 giving us. 25/30 which translates to 83.33 or in my case 8/10. This are the 2 steps I'm uncertain how to do.
1 - Get all ratings from SQL and count them
2 - Determine Average /10 based on all ratings
Current PDO code to pull data from DB as well as Count of how many Reviews each particular user has.
$q = $db->prepare("SELECT * FROM reviews WHERE assigned_id = :review_id ORDER BY review_posted DESC");
$q->execute(array(':review_id' => $_GET['page_id']));
$r = $q->fetchAll(PDO::FETCH_ASSOC);
echo '<br><div class="well">Average Rating</div><br>';
foreach($r as $row) {
$q = $db->prepare("SELECT * FROM users WHERE user_id = :review_user_id");
$q->execute(array(':review_user_id' => $row['user_id']));
$r = $q->fetch(PDO::FETCH_ASSOC);
$q = $db->prepare("SELECT COUNT(*) FROM reviews WHERE user_id = :review_user_id");
$q->execute(array(':review_user_id' => $row['user_id']));
$user_reviews = $q->fetchColumn();
Assume each user give x point (limit by 10), you must sum them up (x) then divide it by rating_times, you get average rating.
For example
User 1 rate 7
User 2 rate 6
User 1 rate 5
=> (7+6+5)/3 = 6
So you just add one more field when user rating called point.
Then use query SUM to SUM point up, divided with query COUNT then done.
forget the (x**/10**).
Finally, use 2 average rating (Price and service), sum of them, divided by 2 and you got overall rating.
Here's what you probably meant to do:
$q = $db->prepare("
SELECT *
FROM review r
JOIN users u ON r.user_id=u.id
JOIN (SELECT user_id, COUNT(1) as count FROM review GROUP BY user_id) uc ON uc.user_id = u.id
WHERE r.assigned_id=:review_id
ORDER BY r.review_posted DESC");
$q->execute(array(':review_id' => $_GET['page_id']));
$r = $q->fetchAll(PDO::FETCH_ASSOC);
foreach ($r as $row) {
// $row should have all fields included in $tables review and users as well as $row[count] would contain the total number of reviews a user made
}
This will include the user's details alongside the rating details for each review with that assigned_id
Edit: Added sum of user reviews as well.
You can use this snippet.
This helped me
https://gist.github.com/tiagofrancafernandes/1c5752ba2ebeb477975c6c016a37fc5c

PHP counting records from other table using id

I have a table prices that looks like this:
id - price - amount
I have an other table winners that keeps what price the users have won. It looks like this:
id - userid - priceid
So the id of my table prices is the sale as the priceid in the winners table.
Now let's say I want the amount of winners that have won price X and price X has id 1 for example. I've tried writing a query but it doesn't seem to make much sense.
$price = "X";
$count = $conn->fetchAll("SELECT winners.id FROM winners INNER JOIN prices ON winners.priceid=prices.id WHERE prices.price='".$price."'");
If anyone can help me out I would appreciate it very much
Many thanks in advance!
If you want the number that have won price X :
$count = $conn->fetchAll("SELECT COUNT(winners.id) AS nb_winners FROM winners INNER JOIN prices ON winners.priceid=prices.id WHERE prices.price='".$price."'");

Collect values from DB, group matching values, count it and use in other code

This is what my customers_basket table looks like:
customers_id | products_id | basket_quantity
3 | 56:3121fefbe6043d6fc12e3b3de2c8fc38 | 3
3 | 56:fb4c9278fcfe6225b58c06711a7e62ef | 1
3 | 56:8e334fce09556108f5416e27154b6c27 | 1
3 | 52:f3b9f38e4ddd18035bc04cd264b0f052 | 1
This is the query I'm using:
$products_in_cart_query = "SELECT products_id FROM customers_basket WHERE customers_id = " . $_SESSION['customer_id'] ."";
$products_in_cart = $db->Execute($products_in_cart_query);
$products_in_cart_model = $products_in_cart->fields['products_id'];
$products_in_cart_model = substr($products_in_cart_model, 0, strpos($products_in_cart_model, ":"));
The end result I get is 56,56,56,52
First of all, how do I use the first line's quantity field? I'd need to list that products_id 3 times since quantity is 3. Therefore, the end result needs to be: 56,56,56,56,56,52
or, for easier understanding (56,56,56),56,56,52
And second, how do I count how many same values I have? In this case, I have 5x56 and 1x52. I need to use those counts in my further calculation.
EDIT: further calculations explained
I need to know how many of each product_id I have and then run something like this:
foreach(product_id) {
$shipping_cost += FIXED_VALUE * basket_qty;
}
To get the basket quantity, you have to select it. It would be best if the first portion of the product ID was stored in a separate column, rather than having to do messy operations like substringing.
Query 1: 2-character codes and corresponding quantities
SELECT SUBSTR(products_id, 1, 2) AS product_code, basket_quantity
FROM Customers_Basket
WHERE customers_id = 3;
Query 2: 2-character codes and summed quantities
SELECT product_code, SUM(basket_quantity) AS total_quantity
FROM (SELECT SUBSTR(products_id, 1, 2) AS product_code, basket_quantity
FROM Customers_Basket
WHERE customers_id = 3
)
GROUP BY product_code;
If you really, really, really desperately want 3 rows of data for the product ID 56:3121fefbe6043d6fc12e3b3de2c8fc38, then you have to know ways to generate rows. They're truly painful in the absence of convenient SQL support (so much so, that you'd do better to select a row in PHP with the quantity and then generate the appropriate number of rows in your array in the client-side (PHP) code). I'm going to assume that some variation on these queries will get you the information you want.

MySQL: Group by two columns and sum

Building an inventory system. I have lots of products and each product has three different variables. So for stock totals I want to group by the two columns (product & size) and sum quantity to get stock total.
product
Size
Quantity
Widget one
2
275
Widget one
2
100
Widget two
3
150
Widget two
2
150
What I want for output:
product
Size
Quantity
Widget one
2
375
Widget two
3
150
Widget two
2
150
I figured out how to group by one column and sum using the code below:
$query = "SELECT product, SUM(Quantity) FROM inventory GROUP BY product";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)){
echo "Total ". $row['product']. " = ". $row['SUM(Quantity)'];
echo "<br />";
}
?>
I am just stuck on grouping by both columns. Is it possible? or should I just create three different products for the of the three sizes and eliminate that column? Thanks.
Based on your example table, it appears you want to be grouping on product rather than id. You merely need to add the Size column to both the SELECT list and the GROUP BY
$query = "SELECT
product,
Size,
SUM(Quantity) AS TotalQuantity
FROM inventory
GROUP BY product, Size";
Note that I have added a column alias TotalQuantity, which will allow you to more easily retrieve the column from the fetched row via the more sensible $row['TotalQuantity'], rather than $row['SUM(Quantity)']

how to find the greatest number from an array

This is the books table on db;
book_ID writer_ID
-------- -----------
1 10
2 10
3 10
4 10
5 10
This is the rates table on the db,
book_ID rate
------- --------
1 4
2 3
2 5
2 1
2 4
3 5
4 2
4 5
4 2
4 4
5 3
now, i have the writer_ID at first, and i have to find all book_ID (connected to that writer_ID) and the average rates of each book_ID from the rates table. finally, i have to find the greatest rate average and its book_ID
this is my code
$query="SELECT * FROM books WHERE seller_id ='$id'";
$result = mysql_query($query);
while ($info = mysql_fetch_array($result)) {
//getaveragerate is the function that returns average of the rates from rates table
$arr = array(ID => $info['book_ID'], average => getaveragerate($info['book_ID']));
}
$greatest_average_and_books_id_number = max($arr); // dont know how to get highest average and its ID together from array
that is my question, sorry but english is not my native language, i am trying my best to explain my problem. sometimes i cant and i just stuck.
thanks for understanding.
Or just let the database do it for you:
SELECT max(fieldname) FROM rates WHERE id='34'
If you are limited as to which functions you can perform (ie using some CRUD class):
SELECT * FROM rates WHERE id='34' ORDER BY id DESC LIMIT 1
You haven't told us what fields from the database will be returned by your query. It also looks like you're filtering (WHERE clause) on key column, which should only return one record. Therefore you can strip out everything you have there and only put:
$greatest_record = 34;
No need for a query at all!
With a little more information on what you're doing and what fields you're expecting:
$query = "SELECT id, rate FROM rates";
$result = mysql_query($query);
$myarray = array();
$greatest_number = 0;
while ($row = mysql_fetch_array($result)) {
myarray[] = $row; // Append the row returned into myarray
if ($row['id'] > $greatest_number) $greatest_number= $row['id'];
}
// Print out all the id's and rates
foreach ($myarray as $row_num => $row) {
print "Row: $row_num - ID: {$row['id']}, Rate: {$row['rate']} <br>";
}
print "Highest ID: $greatest_number";
Note that we maintained what was the greatest number at each row returned from the database, so we didn't have to loop through the $myarray again. Minor optimization that could be a huge optimization if you have tens of thousands of rows or more.
This solution is on the basis that you actually need to use the ID and RATE fields from the database later on, but want to know what the largest ID is now. Anyone, feel free to edit my answer if you think there's a better way of getting the greatest_number from the $myarray after it's generated.
Update:
You're going to need several queries to accomplish your task then.
The first will give you the average rate per book:
SELECT
book_id,
avg(rate) as average_rate
FROM Rates
GROUP BY book_id
The second will give you the max average rate:
SELECT
max(averages.average_rate),
averages.book_id
FROM (
SELECT
book_id,
avg(rate) as average_rate
FROM Rates
GROUP BY book_id
)
as averages
WHERE averages.average_rate = max(averages.average_rate)
This will give you a list of books for a given writer:
SELECT book_id
FROM Books
WHERE writer_id = $some_id
Don't try to do everything in one query. Mixing all those requirements into one query will not work how you want it to, unless you don't mind many very near duplicate rows.
I hope you can use this update to answer the question you have. These SQL queries will give you the information you need, but you'll still need to build your data structures in PHP if you need to use this data some how. I'm sure you can figure out how to do that.

Categories