SUM points from table - php

I have table with files and their have their points/score. Iam trying to summarize those points and print it. I have a where clause for id files, but if I select random files it has same score as others like where clause isnt working.
$id is correct for each file.
This is my query:
$result = mysql_query("SELECT *,SUM(body) FROM soubory, users, hodnoti WHERE
soubory.id='".$id."' AND soubory.users_id = users.id");
hodnoti table
users_ID soubory_id body
14 44 7
15 44 9
And now, if there is no record (in table hodnoti) for soubory_id = 45 the result is same as for 44 despite of where clause.
users table
id nick
14 user1
15 user2
soubory table
id nazev users_id
44 file1 14
45 file2 14
That query should help me print this:
Who uploaded, nazev(title) of the file and then points. But if file2 has no record in table hodnoti, still has score of file1. Hope it helps.

$sql = "SELECT *, SUM(hodnoti.body) as sum FROM soubory
INNER JOIN users ON soubory.users_id = users.id
INNER JOIN hodnoti ON soubory.id = hodnoti.soubory_id
WHERE soubory.id='".$id."' ";
$result = mysql_query($sql);
This query works for me. When i set id=44 and get a result and when set id=45 and get all null value. i have attached two result image. I have just create table and insert your given data and run query on phpmyadmin sql tab query box. You can try this for check your query works or not.

Use JOIN.
$sql = "SELECT *, SUM(hodnoti.body) as sum FROM soubory
INNER JOIN users ON soubory.users_id = users.id
INNER JOIN hodnoti ON soubory.id = hodnoti.soubory_id
WHERE soubory.id='".$id."' ";
$result = mysql_query($sql);
SUGGESTION: Above is a direct answer for your question. Avoid using mysql_* statements as they are deprecated now. Learn mysqli_* or PDO and start implementing that.

Related

Get all the members below me in an mlm module in PHP and MySQL

I have a database, as shown in this, any user can join with any sponsor ID, and they will get their own user ID which can lead the tree further. I want to get details of a particular user_id, say, '2'. I am expecting the output in which the user_id will be (3,4 since 3 is directly linked with 2 and 4 is linked directly with 3 which is linked with 2). Similarly if I select user_id 1, then I would get the resultant user_id (2,3,4,5, where 2 and 5 are directly linked to user_id 1 and 3,4 are indirectly linked to 1).
I have tried almost every possible while loop format, but I just can't get the output. Here is the final bit of my code, because I have deleted most of it:
<?php
include 'config.php';
$current_user='1';
$all = mysqli_query($con,"SELECT * FROM users");
while($all_array = mysqli_fetch_array($all)){
$all_sponsors = $all_array['sponsor_id'];
}
$below_details = mysqli_query($con,"SELECT * FROM users WHERE sponsor_id ='$current_user'");
while ($below_array = mysqli_fetch_array($below_details)){
$below_users = $below_array['user_id'];
}
?>
Any kind of help is appreciated. Feel free to ask me the details if there is any confusion in the question.
You can use a recursive CTE to retrieve all the members below a given id -
WITH RECURSIVE pyramid AS (
SELECT u.* FROM users u WHERE sponsor_id = 1 /* starting sponsor_id */
UNION ALL
SELECT u.* FROM pyramid p JOIN users u ON p.id = u.sponsor_id
)
SELECT * FROM pyramid;

How to properly write query SELECT'ing multiple tables

please advise on query below. I want to select multiple tables. entryId is from table stockTracking. I bet i should use JOIN or smt.. Cheers!
$updateEntryId = $_GET["entryId"];
$query = "SELECT *
FROM stockTracking, loggers, boxes
WHERE entryId ='$updateEntryId'";
$result = mysqli_query($connection, $query);
table
boxes|boxId boxQuantity boxName
2 10 CL64
loggers | loggerId loggerQuantity loggerName
2 10 34242342
stockTracking| entryId time destination reference
2 timestamp Paris 1312
I have updated query to following, however what wrong with my WHERE statement?
As i add WHERE entryId='$updateEntryId' if fails to display any results
$updateEntryId = $_GET["entryId"];
$query = "SELECT *
FROM stockTracking
JOIN loggers
ON entryId=loggerId
JOIN boxes
ON boxId=entryId
WHERE entryId='$updateEntryId'";
Yes, you are right. You should perform a JOIN operation among-st the tables like below. replace some_column in below sample sql code with your actual column name on which you have relationship between the tables
SELECT s.*
FROM stockTracking s
JOIN loggers l ON s.some_column = l.some_column
JOIN boxes b ON b.some_column = s.some_column
WHERE s.entryId ='$updateEntryId'
Try this out:
$updateEntryId = $_GET["entryId"];
$query = "SELECT *
FROM stockTracking s
JOIN loggers l
ON s.entryId=l.loggerId
JOIN boxes b
ON b.boxId=s.entryId
WHERE s.entryId='".$updateEntryId."'";
Join the tables as stated by #rahul but should be done in proper manner .. cheers!
SOLVED.
Problem was in $updateEntryId=$_GET["entryId"];
It had no results, since as search bar was showing http://stock/edit.php?id=2, it was looking for $_GET["id"] and not $_GET["entryId"].

how to call 2 tables from mysql database with php [duplicate]

This question already has answers here:
sorting by high-low price with mysql data
(2 answers)
Closed 7 years ago.
i have 2 tables
page and orders.
$ww = mysqli_query($database->connection,"SELECT * FROM `page`
WHERE `owner` = '$session->u_id'");
while($o = mysqli_fetch_array($ww))
{
$owner = $o['id'];
$result = mysqli_query($database->connection,"SELECT * FROM `orders`
WHERE `owner` = '$owner' ORDER BY id DESC");
while($row = mysqli_fetch_array($result))
{
echo "taxi =".$o['naam']."<br>";
echo $row['id']."<br>";
}
}
the output is
23
21
20
17
26
25
24
22
19
Question is How can i sort high to low like
26
25
24
23
22
21
....
You need to run just one query when selecting from orders, not one query per page (BTW, it helps if you tabulate properly, people can see this then). Even better is to just run one query using a join.
You'll need to post your table structure before we can write any query.
1) you can use inner join to write the query if id column of second table won't be null otherwise use left join
SELECT * FROM `orders` inner join page on orders.id = page.id where owner = $session->u_id;
2) you can use your first query as sub query and put it in second one like this
SELECT * FROM `orders` WHERE exists (SELECT page.id FROM `page` WHERE `owner` = '$session->u_id' and orders.id=page` WHERE `owner` = '$session->u_id' and orders.id= )ORDER BY id DESC.id ) ORDER BY orders.id DESC
Note : if any syntax error is found the forgive me :)-

Picking which data to view in group by

So yesterday, I am trying to sort data in groups made by Group by
I must select which data I want to show in those group
There is list of debts and each person may be in debt in the past but never have more than 1 unpaid debt
I need to know how many times how many times each user have been in debt before this last debt.
This is the column in the data base
Table "Users"
uid | name | date_of_birth
Table "Debt"
uid | debt_duration | paid_count | created_date
I end up with a hack like this in php
$res = mysql_query( "
SELECT * FROM Debt
JOIN Users
WHERE Users.uid = Debt.uid
ORDER BY created_date
GROUP BY Debt.uid");
while( $row = mysql_fetch_array( $res ) ){
$uid = $row['uid'];
$r = mysql_fetch_array( mysql_query("SELECT COUNT(*) FROM Debt WHERE uid = $uid") );
$previous_debts_count = $r[0];
}
This script is quite heavy but fortunately my client doesn't complain.
The script run at around 3 seconds top
But I need to know better ways to do this
sorry for the strange formatting, I am new here ...
I think the query you want is this:
SELECT Users.uid, COUNT(*) as cnt
FROM Debt JOIN
Users
ON Users.uid = Debt.uid
GROUP BY Debt.uid
ORDER BY created_date ;
Just loop through the results and don't use multiple queries for this. Check that Users.uid is the primary key on the users table. And add an index on debt(uid) to improve performance.
First of all, you should never use * in an SQL statement.
It makes the query highly vulnerable to SQL injection.
And I recommend you to use a PDO or a PHP framework.
Try this:
SELECT COUNT(Debt.uid) AS users
FROM Debt
LEFT JOIN Users
ON Users.uid = Debt.uid
GROUP BY Debt.uid

Simple query to perform joining operation

I am performing MySQL functions using PHP for my webpages.
I have got a table
table name -> users
uname oname
john alex
john murray
john joseph
john ray
and another table
table name -> more_info
fname lname more
alex some name some info
murray // //
joseph // //
ray // //
What I am trying to do is to run a query
Retrieve all the oname column values which are matched with uname john
This statement successfully retrieves the oname column values if uname = john
SELECT oname FROM users WHERE uname = 'john '
Now I want a statement something like this, based on the previously retrieved oname column values
SELECT * FROM more_info WHERE fname=oname // previos ones
I guess its Join orinnerJoin but somehow I am unable to get the correct syntax of it or any other simple query to do this.
My approach
I thought to retrieve the oname column values first and then inside a for loop, based on number of rows returned run a query for each column, but this approach eats up my server.
Try this query,
SELECT * FROM `more_info` `i` INNER JOIN `users` `u` ON `i`.`fname`=`u`.`oname` WHERE `u`.`uname`="john"
I think the following query wll help u.
SELECT * FROM `more_info` WHERE `fname` = (SELECT `oname` FROM `users` WHERE `uname` = "john")
You can merge your two queries into one by a simple INNER JOIN
SELECT * FROM more_info mi
INNER JOIN users u ON mi.fname = u.oname
WHERE u.uname = 'john'
If there is some chance of null values in more_info table, then you should use LEFT JOIN instead of INNER JOIN. Otherwise it is not necessary.
SELECT * FROM users A
INNER JOIN more_info B
ON A.oname = B.fname
WHERE uname = 'john'
See the MySQL documentation on the JOIN syntax for details.

Categories