PHP counting records from other table using id - php

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."'");

Related

Sum and join 2 tables

I want to sum and join 2 tables. I am getting a wrong answer. What am i doing wrong please
$stmt = $pdo->query("
SELECT
a.prod_name, a.prod_size,
b.prod_name, b.prod_size,
SUM(b.qty_bought) qty_bot,
SUM(a.prod_qty) qty_received
FROM tbl_distribution a
JOIN tbl_sales_bar b
ON a.staff_id = b.staff_id
WHERE a.staff_id = '$_GET[id]'
GROUP BY b.prod_id
");
WHILE($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo '<tr>
<td>'.$row["prod_name"].'</td>
<td>'.$row["prod_size"].'</td>
<td>'.$row["qty_received"].'</td>
<td>'.$row["qty_bot"].'</td>
<td></td>
</tr>';
}
what i want is to get the sum of quantity bought and the sum of product quantity so that when i minus the product quantity for the quantity bought, i will get the balance which is the difference between the product quantity - quantity bought = available quantity
Thanks
Edit:
let me use images to show what i intend to have as result:
thanks

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

How to get grand total of many tables' totals

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.

Exploding data from mysql using PHP

I have a database table where I am storing all the values from an external xml file. Since my project requirement demands me to deal with this unnormalized data. I need to help to extract data in an appropriate way.
I have two web pages (one for categories) and one for products.My database table looks like this:
**product_id Code Name ProductRange ProductSubRange WebCategory**
1 1002 Lid 30l Crystal;Uni LIDs Household products
2 10433 Casa Basket Silver Casa Casa Hipster BASKET Kitchenware
3 17443 Casa Basket Ice White Casa;Laundry LAUNDRY BASKET Laundry products
4 13443 Garden tub Eden Eden Garden Pots Household products
5 199990 Black Lid 201 Crystal Crystal Lids Household products
The product that belong to more than one productRange is indicated my semicolon(;). For example,above product_id 1 with name "Lid 301" belongs to two Product Ranges "Crystal" and "Uni". Same is for product_id 3. However product 2 belongs to single ProductRange.
MY QUESTIONs:
1) How can I construct a query so that it could return "ProductRange" based on my query_string values of "Webcategory"? For example:
if I get "Household Products" as my WebCategory from query string, it could give me distinct like this:
Household Products
|-Crystal
|-Uni
|-Eden
Laundry Products
|-Casa
|-Laundry
Kitchenware
|-Casa
2) Based on extracted ProductRanges, I want to display products separately in my webpages according to the product range and webcategory. For example, if I choose "Crystal" from above, it could give me Products with product_id "1" and "5" respectively like this:
Household Products|
|-Crystal
|-Lid 301 (product_id=1)
|-Balck Lid 201 (product_id=5)
|-Uni
|-Lid 301 (product_id=1)
|-Eden
|-Garden Tub
Kitchenware|
|-Casa
|-Casa Basket silver
Laundry Products|
|-Casa
|-Casa Basket Ice White
|
|-Laundry
|-Casa Basket Ice White
Can anyone guide me how can I retrieve records from the database and what I will need to do as I am new to programming? I would appreciate if anyone could help me in this regard.
In order to get distinct product ranges based on a give WebCategory input = 'XYZ', you can use the following - don't be intimidated by the numberstable, it's just a helpful table that contains rows each with increasing integer values from 1 ... up to N where N is the maximum number of characters in your ProductRange column. These can be made by hand or using a special insert/select query like the one found here:
http://www.experts-exchange.com/Database/MySQL/A_3573-A-MySQL-Tidbit-Quick-Numbers-Table-Generation.html
SELECT DISTINCT
SUBSTRING(ProductRange FROM number FOR LOCATE(';', ProductRange, number) - number) AS ProductRange
FROM (
SELECT ProductRange, CASE number WHEN 1 THEN 1 ELSE number + 1 END number
FROM (
SELECT mydatabasetable.ProductRange, numberstable.number
FROM mydatabasetable
INNER JOIN numberstable
ON numberstable.number >= 1
AND numberstable.number <= CHAR_LENGTH(mydatabasetable.ProductRange)
WHERE WebCategory = 'XYZ'
) TT
WHERE number = 1 OR (number + 1) <= CHAR_LENGTH(ProductRange)
) TT
WHERE SUBSTRING(ProductRange FROM number FOR 1) = ';'
OR numberstable.number = 1;
In order to retrieve a result set with all values WebCategory, ProductRange and Product for your website you can use the below slightly modified version derived from the above query. So that the results will appear more meaningful at first, I added an ORDER BY clause to keep all same-category, same-product-range products in sequence one after the other. This might or might not be desired as you might prefer to do that in your application/server-script code. In that case you can remove the ORDER BY clause without doing any harm.
SELECT WebCategory,
SUBSTRING(
ProductRange
FROM number
FOR LOCATE(';', ProductRange, number) - number
) AS ProductRange,
Product
FROM (
SELECT WebCategory, ProductRange, Product,
CASE number
WHEN 1 THEN 1
ELSE number + 1
END number
FROM (
SELECT WebCategory, ProductRange, Product, numberstable.number
FROM mydatabasetable
INNER JOIN numberstable
ON numberstable.number >= 1
AND numberstable.number <= CHAR_LENGTH(ProductRange)
) TT
WHERE number = 1 OR (number + 1) <= CHAR_LENGTH(ProductRange)
) TT
WHERE SUBSTRING(ProductRange FROM number FOR 1) = ';'
OR numberstable.number = 1
ORDER BY WebCategory, ProductRange, Product
You are probably going to want to do a GROUP BY clause in your query and maybe an JOIN if the detailed data is in a different table. If I understand you correctly it would look something like this.
SELECT T.WebCategory, T.ProductRange, T2.Product FROM table T
INNER JOIN table2 T2 ON T2.ProductRange = T.ProductRange
WHERE T.WebCategory = 'Household products'
GROUP BY T.WebCategory, T.ProductRange, T2.Product
It is tough to test my query without having a database setup to test against, but something like the above should return what you are looking for. You will of course need to rename your columns based on the actual names in the second table. Overall though, this should get you started if I understood the question correctly.

PHP/SQL Voting and counting up the results

I am writing a script for a car show. Users choose the car number and vote 1-5 on various criteria. There are multiple users voting for the same car, but they can only vote once for each car, I check for this.
Now I have a table of a unique carNumber and 1-5 votes for each criteria, per car.
Here is how I find the total score for each individual users vote
SELECT carNum, exterior+interior+engine AS Score FROM Judge_Votes WHERE catagory = '$catNum' ORDER BY carNum
Reults
CarNum: Score:
18 11
14 8
13 15
12 8
12 11
2 14
I want to add up the total score from each user into a final score result. IE car 12 has 19 total score.
The question I have. How can I find the total score using sql or php?
Just use SUM and ORDER BY:
SELECT carNum, SUM(exterior+interior+engine) AS Score
FROM Judge_Votes
WHERE catagory = '$catNum'
GROUP BY carNum
That should do the "trick"
SELECT carNum, sum(exterior + interior + engine) as Score
FROM Judge_Votes
WHERE gatagory = '$catNum'
GROUP BY carNum
ORDER BY carNum
The following should do the trick I think. The logic is that you group your result per car (GROUP BY carNum) and then use the build in SUM function of SQL.
SELECT SUM(exterior+interior+engine) as totalScore, carNum
FROM Judge_Votes
WHERE catagory = '$catNum'
GROUP BY carNum
ORDER BY carNum;

Categories