Querying a database with a one to many relationship - php

I am making a database that when users register, they pick 3 games they would like to play. the games are stored in a separate table (gameinfo) from the user information table (personalinformation). I am querying with the first game being shown but I would like all three shown for each user. How would I implement showing all the games?
I have tried to create different variables for each game, but that has seemed to not work as I expected and broke. the games when they are stored on the personalinformation table are stored as numbers like 1 or 2. these are linked to the gameinfo table and are the primary key for each game.
Structure of database
https://imgur.com/a/qee9C1t
$conn = mysqli_connect('localhost', 'root', '', 'esportclub');
$sql = "SELECT user_ID, username, Email, Gender, firstName, lastName, gameName FROM personalinformation, gameinfo WHERE game_id = firstGame";
$result = mysqli_query ($conn, $sql);
if (mysqli_num_rows($result) > 0) {
echo "<table>";
while($row = mysqli_fetch_assoc($result)) {
echo " <tr><td> Name: ". $row{"username"}. " </td><td> Email: ". $row{"Email"}. " </td><td> Gender: ". $row{"Gender"}. "</td>" .
"<td> First Name: ". $row{"firstName"}. " </td><td> First Game: ". $row{"gameName"}. "</td><td> Last Name: ". $row{"lastName"}. "</td>" . "</td></tr>" ;
}
echo "</table>";
}
else{
echo "0 results";
}
$conn->close();

As mentioned in my comment, I would create a table to associate users and games by storing unique pairs of user_ID and game_id values. Then I'd JOIN the tables together accordingly.
However, I see that you are storing three game values for each user in the personalinformation table, in columns named firstGame,secondGame, and thirdGame.
In that case, you can JOIN the game table to each of those columns.
So, with your existing structure:
SELECT
p.*,
game1.`gameName` as `firstGame_name`,
game2.`gameName` as `secondGame_name`,
game3.`gameName` as `thirdGame_name`
FROM `personalinformation` p
LEFT JOIN `games` as game1 ON (game1.`game_id` = p.`firstGame`)
LEFT JOIN `games` as game2 ON (game2.`game_id` = p.`secondGame`)
LEFT JOIN `games` as game3 ON (game3.`game_id` = p.`thirdGame`)
WHERE 1; // or WHERE p.`user_ID` = :user_ID;
EDIT
Since many users can own a game and a user can own many games, it sounds like a "many-to-many" relationship.
Here is my preferred method for that type of relationship. One advantage is that you don't need to limit the number of assigned games. That is, a user can own any number of games.
Create a third table to store unique user/game pairs.
It will tells you which games are assigned to which users.
Something like:
CREATE TABLE `user_game` (
`user_id` MEDIUMINT NOT NULL ,
`game_id` MEDIUMINT NOT NULL
);
ALTER TABLE `user_game`
ADD UNIQUE `unique pair` (`user_id`, `game_id`);
Then join the three tables together:
SELECT
u.*,
g.`game_id`,
g.`gameName`
FROM `personalinformation` u
LEFT JOIN `user_game` as ug ON ( ug.`user_id` = u.`user_ID` )
LEFT JOIN `games` as g ON ( g.`game_id` = ug.`game_id` )
WHERE 1;
You'll get back one row for every user/game relationship.
If one user has three games, that user will have three rows in the result, each row including one gameName.
For example:
Name Game
---- -----------------
Jane League of Legends
Jane Minecraft
Fred Dota 2
Alex Minecraft
Alex War Dragons
Alex Fortnite
More complex display might require some processing:
<?php
$users = array();
while($row= mysqli_fetch_object($result)) {
$uid = $row->user_ID;
// if this user isn't in the array...
if (!array_key_exists($uid,$users)) {
// ... create a user entry ...
$user = new stdClass();
$user->firstname = $row->firstName;
// ... and add it to the user array.
$users[$uid] = $user;
}
// if this row has a valid game ...
if (!empty($row->game_id)) {
// ... create a game entry ...
$game = new stdClass();
$game->id = $row->game_id;
$game->name = $row->gameName;
//.. and add the game to the user's entry
$users[$uid]->games[$game->id]=$game;
}
}
For a structure like this:
Array
(
[1] => stdClass Object
(
[firstname] => Jane
[games] => Array
(
[1] => stdClass Object
(
[id] => 1
[name] => Leage of Legends
)
[2] => stdClass Object
(
[id] => 2
[name] => Minecraft
)
)
)
[2] => stdClass Object
(
[firstname] => Fred
[games] => Array
(
[3] => stdClass Object
(
[id] => 3
[name] => Dota 2
)
)
)
[3] => stdClass Object
(
[firstname] => Alex
[games] => Array
(
[2] => stdClass Object
(
[id] => 2
[name] => Minecraft
)
[4] => stdClass Object
(
[id] => 4
[name] => War Dragons
)
[5] => stdClass Object
(
[id] => 5
[name] => Fortnite
)
)
)
)

Related

How to query employee details and relate their performance metrics?

I am fetching the id, first name, and last name of all employees that are approved and not archived. Then I am looping these results and using the ids to query other tables to collect some count data.
I tried the below code, but I am not getting the expected output.
$queryEmp = "
SELECT id, firstname, lastname
FROM tbl_employee as e
WHERE is_archive=0 and is_approved=1
";
$getQuery= $this->db->query($queryEmp);
$result= $getQuery->result();
foreach ($result as $key=> $value) {
//echo "<pre>";
print_r($value);
$day = "MONTH(date_of_created) = DATE(CURRENT_DATE())";
$group = "f_id IN (SELECT MAX(f_id) FROM tbl_fileStatus GROUP BY f_bankid)";
$condiion = "and ba.createdby='" . $value->id . "' and " . $day ." and " . $group;
$query2 = "
select
(SELECT COUNT(c_id)
FROM tbl_lead
WHERE leadstatus='1' AND ".$day.") as confirmCount,
(SELECT COUNT(f_id)
FROM tbl_fileStatus as fs
join tbl_bankdata as ba on ba.bank_id=fs.f_bankid
WHERE fs.f_filestatus=1 " . $condiion . ") as disbursed,
(SELECT COUNT(f_id)
FROM tbl_fileStatus as fs
join tbl_bankdata as ba on ba.bank_id=fs.f_bankid
WHERE fs.f_filestatus=2 ".$condiion.") as filesubmit
";
# code...
$getQuery2= $this->db->query($query2);
$result2[]=$getQuery2->result();
}
echo "<pre>";
print_r(result2);
$result looks like this:
Array (
[0] => stdClass Object (
[id] => 1
[firstname] => xyz
[lastname] => xyz
)
...
)
Second query output:
Array (
[0] => Array (
[0] => stdClass Object (
[fallowCall] => 0
[confirmCount] => 0
[disbursed] => 0
[filesubmit] => 0
)
)
...
)
How can I produce the correct results which relate respective employees with with their performance metrics? Either this structure:
Array (
[0] => stdClass Object (
[id] => 1
[firstname] => xyz
[lastname] => xyz
[somename] => (
[fallowCall] => 0
[confirmCount] => 0
[disbursed] => 0
[filesubmit] => 0
)
)
...
)
Or this structure:
Array (
[0] => stdClass Object (
[id] => 1
[firstname] => xyz
[lastname] => xyz
[fallowCall] => 0
[confirmCount] => 0
[disbursed] => 0
[filesubmit] => 0
)
...
)
I have added the my table structure and some sample data here: https://www.db-fiddle.com/f/8MoWmKPuzTrrC3DQJsiX35/0
some notes here
1) createdby is the id of table tbl_employee
2) lead_id in the bank table is the c_id of the table tbl_lead
3) f_bankid in the tbl_fileStatus is the bank_id of the table tbl_bankdata
There is actually no need to create the additional depth/complexity just to hold the count data. Furthermore, by using a combination of LEFT JOINs to connect the related tables and apply your required conditional rules, you can achieve your desired result by making just one trip to the database. This will without question provide superior efficiency for your application. LEFT JOINs are important to use so that counts can be zero without excluding employees from the result set.
Also, I should point out that your attempted query was mistakenly comparing a MONTH() value against a DATE() value -- that was never going to end well. :) In fact, to ensure that your sql is accurately isolating the current month from the current year, you need to be also checking the YEAR value.
My recommended sql:
SELECT
employees.id,
employees.firstname,
employees.lastname,
COUNT(DISTINCT leads.c_id) AS leadsThisMonth,
SUM(IF(fileStatus.f_filestatus = 1, 1, 0)) AS disbursedThisMonth,
SUM(IF(fileStatus.f_filestatus = 2, 1, 0)) AS filesubmitThisMonth
FROM tbl_employee AS employees
LEFT JOIN tbl_lead AS leads
ON employees.id = leads.createdby
AND leadstatus = 1
AND MONTH(leads.date_of_created) = MONTH(CURRENT_DATE())
AND YEAR(leads.date_of_created) = YEAR(CURRENT_DATE())
LEFT JOIN tbl_bankdata AS bankData
ON employees.id = bankData.createdby
LEFT JOIN tbl_fileStatus AS fileStatus
ON bankData.bank_id = fileStatus.f_bankid
AND MONTH(fileStatus.date_of_created) = MONTH(CURRENT_DATE())
AND YEAR(fileStatus.date_of_created) = YEAR(CURRENT_DATE())
AND fileStatus.f_id = (
SELECT MAX(subFileStatus.f_id)
FROM tbl_fileStatus AS subFileStatus
WHERE subFileStatus.f_bankid = bankData.bank_id
GROUP BY subFileStatus.f_bankid
)
WHERE employees.is_archive = 0
AND employees.is_approved = 1
GROUP BY employees.id, employees.firstname, employees.lastname
The SUM(IF()) expression is a technique used to execute a "conditional count". "Aggregate data" is formed by using GROUP BY and there are specialized "aggregate functions" which must be used to create linear/flat data from these clusters/non-flat collections of data. fileStatus data is effectively piled up upon itself due to the GROUP BY call. If COUNT(fileStatus.f_filestatus) was called, it would count all of the rows in the cluster. Since you wish to differentiate between f_filestatus = 1 and f_filestatus = 2, an IF() statement is used. This is doing the same thing as COUNT() (adding 1 for every qualifying occurrence), but it is different from COUNT() in that it does not count specific rows (within the scope of the cluster) unless the IF() expression is satisfied. Another example.
Here is a db fiddle demo with some adjustments to your supplied sample data: https://www.db-fiddle.com/f/8MoWmKPuzTrrC3DQJsiX35/4 (The result set will only be "good" while the current is June of this year.)
After saving the above string as $sql, you can simply execute it and loop through the array of objects like this:
foreach ($this->db->query($sql)->result() as $object) {
// these are the properties available in each object
// $object->id
// $object->firstname
// $object->lastname
// $object->leadsThisMonth
// $object->disbursedThisMonth
// $object->filesubmitThisMonth
}

How to use find in set for user rankings based on score?

I have query like this,
SELECT * FROM users ORDER BY score
So, the result is like this.
Array
(
[0] => stdClass Object
(
[userid] => 3
[user] => John Doe
[score] => 50
)
[1] => stdClass Object
(
[userid] => 1
[user] => Mae Smith
[score] => 38
)
[2] => stdClass Object
(
[userid] => 2
[user] => Mark Sam
[score] => 26
)
)
But, I want to add a rank using find_in_set query. So the result might be like this. So that the user can view their ranks when they login to their account.
Array
(
[0] => stdClass Object
(
[userid] => 3
[user] => John Doe
[score] => 50
[rank] => 1
)
[1] => stdClass Object
(
[userid] => 1
[user] => Mae Smith
[score] => 38
[rank] => 2
)
[2] => stdClass Object
(
[userid] => 2
[user] => Mark Sam
[score] => 26
[rank] => 3
)
)
I tried this one.
$listOfUser = array();
foreach($users as $user) {
$listOfUser[] = $user->userid;
}
And used another query
$userid = 2 // => id of loggedin user
SELECT *, find_in_set($userid, $listOfUser) as rank FROM users where userid=$userid ORDER BY score
So, I got this result
Array
(
[1] => stdClass Object
(
[userid] => 2
[user] => Mark Sam
[score] => 26
[rank] => 3
)
)
Which is somehow correct. But, is there another way of querying that result using only one SQL query and without using foreach loop?
Something like this.
$userid = 2 // => id of loggedin user
SELECT *, find_in_set($userid, (SELECT * FROM users ORDER BY score)) as rank FROM users where userid=$userid ORDER BY score
But I got this error Subquery returns more than 1 row
If You don't insist on using find_in_set, you can get result with simple join. You ask for list of users (p) and for each user you ask, how many users have better score than him or her (c):
SELECT p.userid, COUNT(c.userid) AS rank
FROM users AS p
LEFT JOIN users AS c ON c.score > p.score
GROUP BY p.userid
This works even if you add other conditions, like WHERE p.userid = 123.
If more users have the same score, the ranks would look like 0,1,2,2,2,5,6.
In your query, you can add counter, like this:
set #n:=0;
SELECT #i := #i + 1 AS rank, * FROM users ORDER BY score
The rank here is relative to the score distribution across all users. I believe you should try something originally proposed in this answer:
SELECT users.*,
#rownum := #rownum + 1 as rank
FROM users
CROSS JOIN (select #rownum := 0) r
ORDER BY score DESC
What it does is basically order all users by score, and assign each of them an incremental value "rank". So the top scorer would have a rank of 1, the second scorer would have a rank of 2 etc.
Keep in mind that this solution is not "fair" - each user will have a different rank, even if all users have the same score. If you try to rank users as they do in sports (if two top competitors have the same score, they both take 1st place, and the next best competitor takes 3rd place, not second), you should think of a different solution.

Update multiple rows in database based on multiple checkboxes and inputs

I have array below and I need to update database according to this.
It should be something like example code below but I don't know how to do it correctly:
UPDATE productPercent SET percent="$percent" WHERE
store="$store" AND
startDate>"$start_date" AND
endDate<"$end_date" AND
storeGroup="$storeGroup" AND
productGroup="$product_group" AND
productName LIKE '$search%'
I need to check for each store, store group, product (if contains word) and product group and then update productPercent table. Percent, product group, store group, product name and store are in different tables so some kind of inner join is needed.
I need some directions regarding this because I don't know how to start, thank you.
Array
(
[percent] => 3
[store] => Array
(
[0] => 36
[1] => 45
[2] => 56
)
[start_date] => 2015-02-09
[end_date] => 2015-03-31
[storeGroup] => Array
(
[0] => 2
[1] => 4
)
[product_group] => Array
(
[0] => 13
[1] => 31
[2] => 32
)
[search] => iphone
[setPercent] => Submit
)
UPDATED: data model - tableName: columns(connected tables)
store: id,name,startDate,endDate
storeGroup: id,storeGroupID(in table storeGroupName: id,name),storeID
productGroup: id,productID(in table productName: id,name),groupID(in table productGroupName: id,name)
productName: id,name
productPercent: id,productID,storeID,percent
$pdoHandle = $this->getPDOHandle();
$searchword = 'iphone';
$sql = "UPDATE
productPercent
inner join store on productPercent.storeID=store.id
inner join storeGroup on storeGroup.storeID=store.id
inner join productGroup on productGroup.id=storeGroup.groupID
inner join productName on productPercent.productID=productName.id and productGroup.productID=productName.id
SET percent=:percent
WHERE productName.name like :searchword";
$pdo->prepare($sql);
$pdo->setAttribute('percent', floatval($percent/100));
$pdo->setAttribute('searchword', $searchword . '%');

MySQL pulling information from multiple table issue

I'm trying to access information from 2 different tables and its retrieving the information but it all so pulling in user information multiple times pending how many fruits listed in table tbl_fruits.
like to be able to display user information once and pull what ever number of fruits associated with the user at the same time.
2 tables:
tbl_users:
userid
firstname
lastname
tbl_fruits:
userid
fruit
in the example code userID 4 has 3 fruits associated with him in tbl_fruit. As you can see from the results below the user information is listed multiple times. How can I rewrite the code so that the user information is pulled once and the fruits show up 3 times.
$clientID = "4";
try
{ $stmt = $dbcon1 ->query("SELECT
tbl_fruits.fruit,
tbl_users.userid,
tbl_users.firstname,
tbl_users.lastname
FROM tbl_users
LEFT JOIN tbl_fruits
ON tbl_fruits.userid = tbl_users.userid
WHERE tbl_users.userid = '$clientID' ");
$testArray = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
catch(PDOException $e)
{ echo $e->getMessage(); }
echo '<pre>';
print_r($testArray);
echo '</pre>';
results
array
(
[0] => Array
(
[fruit] => Apple
[userid] => 4
[firstname] => John
[lastname] => Smith
)
[1] => Array
(
[fruit] => Orange
[userid] => 4
[firstname] => John
[lastname] => Smith
)
[2] => Array
(
[fruit] => Banana
[userid] => 4
[firstname] => John
[lastname] => Smith
)
)
Change your query as below:
{ $stmt = $dbcon1 ->query("SELECT
count(tbl_fruits.userid)
tbl_users.userid,
tbl_users.firstname,
tbl_users.lastname
FROM tbl_users
LEFT JOIN tbl_fruits
ON tbl_fruits.userid = tbl_users.userid
WHERE tbl_users.userid = '$clientID'
GROUP BY tbl_users.userid ");
The count(tbl_fruits.userid) part counts the number of unique rows with that row's value of tbl_fruits.userid, while the GROUP BY tbl_users.userid part eliminates the duplicates.
Be sure to put an index on tbl_users.userid and tbl_fruits.userid for best performance.

MySQL: fetch a row and multiple related rows - possible?

Let's say I have one table: "cars" with 3 fields: id, brand, cost.
There's a second table: "models" with 3 fields: id, brand, model_name.
Each "cars" row can have multiple related "models" rows.
Is it possible to do an sql-select whose output looks like this?
edit: I use PHP for the database querys
array(
[0] => array(
[id] => 1
[brand] => mercedes
[cost] => 1000
[models] => array(
[0] => array(
[id] => 1
[brand] => mercedes
[model_name] => slk
)
[1] => array(
[id] => 2
[brand] => mercedes
[model_name] => clk
)
[2] => array(
[id] => 3
[brand] => mercedes
[model_name] => whatever
)
)
)
)
You need to add a foreign key relation to the models table, say car_id. Then:
SELECT * FROM cars JOIN models ON car_id = models.id;
This will output something similar to what you are looking for.
Assuming you are using PHP, using the output:
$query= "SELECT * FROM cars JOIN models ON car_id = models.id";
$r= #mysqli_query($dbc, $query);
while ($row= mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$carstuff['id']=$row[id];
$carstuff['brand']=$row[brand];
$carstuff['cost']=$row[cost];
$carstuff[$row['models']][]=$row['model_name'];
}
var_dump($carstuff);
Note, that the id, brand and cost are repeatedly overwritten, but that is okay because they are overwritten with the same information. I'm not too sure about the cleanliness of the code, but that is the basic idea.
Try this:
Query:
SELECT c.ID, c.brand,c.cost, GROUP_CONCAT(model_name SEPARATOR '","') as models
, GROUP_CONCAT(m.ID SEPARATOR ',') as MID
, GROUP_CONCAT(m.brand SEPARATOR '","') as mbrand
FROM cars c
LEFT OUTER JOIN model m
ON m.brand = c.brand
GROUP BY brand;
Output:
ID BRAND COST MODELS MID MBRAND
1 audi 1000 m11","m22 4,5 audi","audi
1 mercedes 1200 m1","m2","m3 1,2,3 mercedes","mercedes","mercedes
Now in your php code you can process the MODEL,MID and MBrand
(By using explode)
$modelArray = explode(" ,", $row["MODELS");
SQLFIDDLE

Categories