Guidance with a SQL query - results duplicating - php

Really need some guidance, I have a website where people can upload images to competitions and they get a result (marks), I want to pull out a LEADERSHIP BOARD to see how everyone is doing. However the SQL Query I have has people names duplicated, could someone tell me where to alter my query so the results for say 1 person entering 3 competitions are added up, and only the TOTAL marks are stated once in the output. The results are kept in tblMembEntComp fldResult.
What I'm currently getting:
My PHP Code:
<p><b>LEADERSHIP BOARD</b></p>
<?php
$query = "SELECT `tblMember`.`fldFName`, `tblMember`.`fldSName`, `tblMembEntComp`.`fldResult` FROM `tblMember` AS `tblMember` JOIN `tblMembEntComp` as `tblMembEntComp` ON `tblMember`.`fldMemberID` = `tblMembEntComp`.`fldMemberID`ORDER BY `fldResult` DESC";
$result = $conn -> query($query);
while($row = $result -> fetch_assoc())
{
echo $row['fldFName']." ".$row['fldSName']." ".$row['fldResult']."<br>";
}
?>
UPDATE:
I have tried the GROUP BY function as suggested by user below however I am getting thrown the error:

You seem to want an aggregation query. Something like:
SELECT m.fldSName, SUM(mec.fldResult) as fldResult
FROM tblMember m JOIN
tblMembEntComp mec
ON m.fldMemberID =mec.fldMemberID
GROUP BY m.fldSName
ORDER BY SUM(mec.fldResult) DESC

You should group by query by tblMember primary key as below:
<?php
$query = "SELECT `tblMember`.`fldFName`, `tblMember`.`fldSName`, `tblMembEntComp`.`fldResult`, `tblMember`.`fldId` FROM `tblMember` AS `tblMember` JOIN `tblMembEntComp` as `tblMembEntComp` ON `tblMember`.`fldMemberID` = `tblMembEntComp`.`fldMemberID` GROUP BY `tblMember`.`fldId` ORDER BY `fldResult` DESC";
$result = $conn -> query($query);
while($row = $result -> fetch_assoc())
{
echo $row['fldFName']." ".$row['fldSName']." ".$row['fldResult']."<br>";
}
?>
You can update group by field as your primary key. Hope it helps you :)

Related

Get userID from database

I have a simple blog where I'm practicing some php and mysql. I'm trying to display the username of the post author (you know where it says posted by Author).
I have two tables blog_members and blog_posts which are related 1 to many so I got a memberID field into the blog_posts. I'm trying to get the username of the member who's the author of the post.
I was thinking to do a join or something but I can't figure this out.
Here's what I was trying to do but it's not working because I'm sure I'm not using it properly.
$query1 = "SELECT username from blog_members JOIN blog_posts ON memberID = memberID ";
$result1 = mysqli_query($link, $query1);
$row1 = mysqli_fetch_array($result1);
PS: I got it working one way by using SESSION to get the userID but that works only if the user is logged is which is not the case, I want to display the name in any case.
Thanks!
Use inner join this way
And with a proper sanitize use $your_user_id for match
$query1 = "SELECT username
from blog_members
INNER JOIN blog_posts ON blog_members.memberID = blog_posts.memberID
WHERE blog_posts.memberID = '" .$your_user_id . "';";
JOIN syntax is wrong in your query.
Use following query:
$query1 = "SELECT username from blog_members JOIN blog_posts ON blog_members.memberID = blog_posts.memberID ";
$result1 = mysqli_query($link, $query1);
$row1 = mysqli_fetch_array($result1);
Try something like this, usng INNER JOIN :
$query1 = "SELECT blog_members.username FROM blog_members INNER JOIN blog_posts ON blog_members.memberID = blog_posts.memberID ";
reference : http://www.w3schools.com/sql/sql_join.asp
Here is a solution using a simple WHERE condition (same performance Explicit vs implicit SQL joins) :
SELECT a.username FROM blog_members a, blog_posts b WHERE a.memberID = b.memberID
But if you need more information about MySQL Join : https://www.sitepoint.com/understanding-sql-joins-mysql-database/
Hope this helps !

Counting the number of times each variable appears in table

Basically, I am seeking to know if there is a better way to accomplish this specific task.
Basically, what happens is I query the db for a list of "project needs" -- These are each uniquer and only appear once.
Then, I search another table to find out how many members have the required "skills - which are directly correlated to the project needs".
I accomplished exactly what I was trying to do by running a second query and then inserting them into an array like this:
function countEachSkill(){
$return = array();
$query = "SELECT DISTINCT SKILL_ID, SKILL_NAME FROM PROJECT_NEEDS";
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_num_rows($result);
while($row = mysql_fetch_assoc($result)){
$query = "SELECT COUNT(*) as COUNT FROM MEMBER_SKILLS WHERE SKILL_ID = '".$row['NEED_ID']."'";
$cResult = mysql_query($query);
$cRow = mysql_fetch_assoc($cResult);
$return[$row['SKILL_ID']]['Count'] = $cRow['COUNT'];
$return[$row['SKILL_ID']]['Name'] = $row['SKILL_NAME'];
}
arsort($return);
return $return;
}
But I feel like there has to be a better way (perhaps using some kind of join?) that would return this in a result set to avoid using the array.
Thanks in advance.
PS. I know mysql_ is depreciated. It is not my choice on which to use.
SELECT P.SKILL_ID, P.SKILL_NAME, COUNT(M.SKILL_ID) as COUNT FROM PROJECT_NEEDS P INNER JOIN MEMBER_SKILLS M
ON P.SKILL_ID=M.SKILL_ID
GROUP BY P.SKILL_ID, P.SKILL_NAME
I've adjusted Nriddens answer to accomodate for the select distinct, Im under the belief that his adjustment would be ok given SKILL_ID is a primary key
function countEachSkill(){
$return = array();
$query = "
SELECT
COUNT(*) AS COUNT,
PROJECT_NEEDS.SKILL_NAME,
PROJECT_NEEDS.SKILL_ID
FROM
(SELECT DISTINCT
SKILL_ID, SKILL_NAME
FROM
PROJECT_NEEDS) AS PROJECT_NEEDS
INNER JOIN
MEMBER_SKILLS
ON
MEMBER_SKILLS.SKILL_ID = PROJECT_NEEDS.SKILL_ID
GROUP BY PROJECT_NEEDS.SKILL_ID";
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_num_rows($result);
while($row = mysql_fetch_assoc($result)){
$return[$row['SKILL_ID']]['Count'] = $row['COUNT'];
$return[$row['SKILL_ID']]['Name'] = $row['SKILL_NAME'];
}
arsort($return);
return $return;
I am subquerying on the select distinct because I dont believe you have a dedicated skills table with an auto inc primary key, if that was there I wouldn't be using a subquery.
Can you test this query
select project_needs.*,count(members_skills.*) as count from project_needs
inner join members_skills
on members_skills.skill_id=project_needs.skill_id Group by project_needs.skill_name, project_needs.skill_id

php mysql query combination

I first search all questions info. from "question" table including title, content, user etc.
the Code:
$sql = "select * FROM question where id>0 ORDER BY id ASC";
$result1 = mysql_query($sql);
$res=Array();
And then I want to search the user's point from "user" table. So I must search point for each user in each row from the result1
The Code:
while($rows=mysql_fetch_assoc($result1))
{
$res[]=$rows;
$user = $rows['user'];
$sql2 = "select point from user where name='$user'";
$result2 = mysql_query($sql2);
}
My problem is how to combine all the users' point(result2) with the questions info.(result1) together so that I can return a json for each row.
Use left join, as my understanding this work for you
$sql = "SELECT q.*, u.point AS point FROM question AS q LEFT JOIN user AS u ON q.user = u.name WHERE q.id > 0 ORDER BY q.id ASC";
$result = mysql_query($sql);
It's better go with the joins here i am giving you the query.i hope it may helps you
select * from question q,user u where q.id>0 ORDER BY id ASC
try something like this:using left join
select question.*,user.point FROM question left join user on user.name= question.name where id>0 ORDER BY id ASC

PHP get largest number from mysql table

i have counted the number of voters that voted for certain candidate i want to display which one got the highest voting number. i tried to store them in variables so i can use max() method but i got the error "undefined ".any help please
<?php
$query="select count(*) as total from voting Where ca_id=1";
//ca_id is the candidate id that voter choose
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
echo"$row[total]<br>";
$query="select count(*) as total2 from voting Where ca_id=2";
$result = mysql_query($query);
$row2 = mysql_fetch_assoc($result);
echo"$row2[total2]<br>";
$query="select count(*) as total3 from voting Where ca_id=3";
$result = mysql_query($query);
$row3 = mysql_fetch_assoc($result);
echo"$row3[total3]<br>";
$query="select count(*) as total4 from voting Where ca_id=5";
$result = mysql_query($query);
$row4 = mysql_fetch_assoc($result);
echo"$row4[total4]<br>";
?>
You don't need to perform four queries for this. You could just use a single query. In your case, you could do:
select ca_id, count(*) as counter from voting group by ca_id order by counter desc
And you can get your result with a single query
As mentioned, PDO is a better alternative in this case for your database-related calls
SELECT count(1) co, ca_id FROM voting GROUP BY ca_id ORDER BY co DESC LIMIT 5
Please, don't use mysql_* functions in new code. They are no longer maintained and the deprecation process has begun on it. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which.
You could use something like which uses the MySQLi extension.
<?php
$mysqli = new mysqli('host', 'user', 'pass', 'db');
$sql = "SELECT COUNT(votes) as vote_count, ca_id as candidate_id FROM voting GROUP BY ca_id ORDER BY vote_count DESC";
$result= $mysqli -> query($sql);
// Error Checking
if($mysqli -> error){
echo 'Error: '.$mysqli -> error;
exit;
}
while($row = $result -> fetch_object()){
// Print out each candidate ID and the amount of votes they had.
echo 'Candidate ID: '.$row -> candidate_id.', Votes: '.$row -> vote_count.'<br/>';
// If you want to just show the highest voted candidate - put the data in an array
$votes[$row -> vote_count] = $row -> candidate_id;
}
echo max(array_keys($votes));
This will also cut the amount of queries your running down to just 1.
first of all use group by to retrieve all data in one query, instead of querying for each of the candidates:
SELECT ca_id, count(*) as total FROM voting GROUP BY ca_id
if you need a top voted id use:
SELECT ca_id, count(*) as total FROM voting GROUP BY ca_id SORT BY total
DESC LIMIT 1
Note: not the most efficient solution but will be way faster then querying for each ca_id.

add value to result from mysql query that will be JSON encoded in PHP?

I would like to add a value to each row that I get from my query depending on if a row exist in another table. Is there a smart way to achieve this?
This is the code I have:
$sth = mysql_query("SELECT tbl_subApp2Tag.*, tbl_tag.* FROM tbl_subApp2Tag LEFT JOIN tbl_tag ON tbl_subApp2Tag.tag_id = tbl_tag.id WHERE tbl_subApp2Tag.subApp_id = '".$sub."' ORDER BY tbl_tag.name ASC");
if(!$sth) echo "Error in query: ".mysql_error();
while($r = mysql_fetch_assoc($sth)) {
$query = "SELECT * FROM tbl_userDevice2Tag WHERE tag_id='".$r['id']."' AND userDevice_id='".$user."'";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result)) {
$r['relation'] = true;
$rows[] = $r; //Add 'relation' => true to this row
} else {
$r['relation'] = false;
$rows[] = $r; //Add 'relation' => false to this row
}
}
print json_encode($rows);
Where the //Add ... is, is where I would like to insert the extra value. Any suggestions of how I can do this?
I'm still a beginner in PHP so if there are anything else that I have missed please tell me.
EDIT: Second query was from the wrong table. This is the correct one.
Edited Edited below query to reflect new information because I don't like leaving things half-done.
$sth = mysql_query("
SELECT
tbl_subApp2Tag.*,
tbl_tag.*,
ISNULL(tbl_userDevice2Tag.userDevice_id) AS relation
FROM tbl_subApp2Tag
LEFT JOIN tbl_tag
ON tbl_tag.id = tbl_subApp2Tag.tag_id
LEFT JOIN tbl_userDevice2Tag
ON tbl_userDevice2Tag.tag_id = tbl_tag.id
AND tbl_userDevice2Tag.userDevice_id = '".$user."'
WHERE tbl_subApp2Tag.subApp_id = '".$sub."'
ORDER BY tbl_tag.name ASC
");
Though the above feels like the LEFT JOIN on tbl_tag is the wrong way around, but it's hard to tell as you are vague on your eventual aim. For example, if I was to assume the following
Tags will always exist
subApp2Tag will always exist
You want to know if a record in tbl_userDevice2Tag matches the above
Then I would do the following instead. The INNER JOIN means that it won't worry about records in tbl_tag that are not on the requested subApp_id which in turn will limit the other joins.
$sth = mysql_query("
SELECT
tbl_subApp2Tag.*,
tbl_tag.*,
ISNULL(tbl_userDevice2Tag.userDevice_id) AS relation
FROM tbl_tag
INNER JOIN tbl_subApp2Tag
ON tbl_subApp2Tag.tag_id = tbl_tag.id
AND tbl_subApp2Tag.subApp_id = '".$sub."'
LEFT JOIN tbl_userDevice2Tag
ON tbl_userDevice2Tag.tag_id = tbl_tag.id
AND tbl_userDevice2Tag.userDevice_id = '".$user."'
ORDER BY tbl_tag.name ASC
");
you have to do all the job in a single query.
Why can't you just $r['append'] = "value"; before adding $r to the array?

Categories