pull data from two tables with one query/ select statement - php

I am pulling one column from the USERS table but now I wanna pull columns from the MONEY table. How do I accomplish this?
sample database
USERS TABLE
userID = 33
nestEgg = 600000
MONEY TABLE
userID = 33
monthlyContributions = 500, 250, 300
totalContributions =
<?php
include 'inc/connect.php';
$query = "SELECT * FROM USERS WHERE userID = '$userID'";
$result = mysqli_query($link,$query);
$row = mysqli_fetch_assoc($result);
?>

If I'm not mistaken, you're asking to create a column in MONEY which is the sum of nestEgg and monthlyContributions. I'm a total newbie, but I think getting the sum, followed by the insert, should look like:
SELECT (SELECT SUM(nestEgg) FROM USERS) + (SELECT SUM(monthlyContributions) FROM MONEY)
INSERT INTO MONEY(totalContributions)
If you only want the sum from the monthly contributions, then it should just be:
SELECT SUM(monthlyContributions) FROM MONEY
INSERT INTO MONEY(totalContributions)
If I'm not mistaken.

Related

Add MySQL Count Column to PHP/HTML Table

I'm developing a website using HTML, PHP and MySQL to access a database. On one page I present a table with data from that database. This is some of the code I'm using:
$sql1 = "SELECT * FROM MyTable ORDER BY ID ASC";
$rs1 = mysqli_query($link,$sql1);
(...)
while($row1 = mysqli_fetch_assoc($rs1)) {
echo "<tr><td>".$row1['ID']."</td><td>".$row1['Field1']."</td><td></td><td>".$row1['Field2']."</td><td>".$row1['Field3']."</td></tr>\n" ;
}
Notice the empty <td></td>? That's because I want to have there the number of time a given ID appears on two other tables (there are foreign keys involved, obviously). I have sorted out the code I need for that:
$sql2 = "SELECT (SELECT COUNT(*) FROM MyTable2 WHERE ID2=$row1['ID'])+(SELECT COUNT(*) FROM MyTable3 WHERE ID2=$row1['ID']) AS total";
However, I'm struggling with figuring out a way to add this result to the other table. Any help?
try with this.. it inserts the total to an table after selecting the count.
"INSERT INTO total_table (total)
SELECT (SELECT COUNT(*) FROM MyTable2 WHERE ID2=$row1['ID'])+(SELECT COUNT(*) FROM MyTable3 WHERE ID2=$row1['ID']) AS total
WHERE cid = 2"

Avoid data redundancy in a friends table

I am trying to design a very simple table that stores the data of friends in a community.
Therefor I store the userId of 2 friends respectively.
Goal
User wants to load his/her friends list.
t_friends Option 1:
Query
SELECT * FROM t_friend WHRE user_id = 10
10 is the current userId of the user which is looking for his friends list and he has 1 friend userId(20)
This way userId (10) finds his friend (20) BUT what if userId(20) were looking for his friends?
The query is coupled with userId.
That leads me to another design that contains redundant data:
t_friends option 2:
userId (10) loads now:
SELECT * FROM t_friend WHRE user_id=10
Similiar to that the query for userId(20) would then be:
SELECT * FROM t_friend WHRE user_id=20
But what about the redundancy? That leads me then to that query using table design option 1:
SELECT * FROM t_friend WHERE user_id=10 OR friend_id=10
I have a feeling that there is a smarter way to solve that. Do You have any experiences with that structure?
Thanks
Add field friendship_key:
ALTER TABLE t_friend ADD friendship_key decimal(22,11);
CREATE UNIQUE INDEX friendship_key_unique ON t_friend (friendship_key);
And php part:
$friends = [$userId, $friendId];
$key = min($friends).'.'.max($friends);
$q = "SELECT * FROM t_friend WHERE friendship_key = ".$key;
insert:
$friends = [$userId, $friendId];
$key = min($friends).'.'.max($friends);
$q = "INSERT INTO t_friend (friendship_key, userId, friendId) VALUES (".implode(',', [$key, $userId, $friendId]).")";
Instead of using VARCHAR for friendship key I've used decimal to minimize data for relation key.
To keep it simple just create functions:
function insertFriendship($user1, $user2) {
$key = min([$user1, $user2]).'.'.max([$user1, $user2]);
$q = "INSERT INTO t_friend (friendship_key, userId, friendId) VALUES (".implode(',', [$key, $user1, $user2]).")";
mysql_query($q);
}
function getFriendsOf($user) {
$q = "SELECT * FROM t_friends WHERE ".$user." IN (userId, friendId)";
return mysql_query($q);
}
function areFriends($user1, $user2) {
$key = min([$user1, $user2]).'.'.max([$user1, $user2]);
$q = "SELECT 1 FROM t_friends WHERE friendship_key = ".$key." LIMIT 1";
$q = mysql_query($q);
return (mysql_num_rows($q)>0);
}
I think this is the only way to store data about the relationships. When you are storing the relationship try to store the min value as the userId and max value as the friendId. make both values altogether unique and you will not get any duplicate values. When you search for users use something like below
SELECT * FROM t_friend WHERE user_id=10 OR friend_id=10
You may want to use the following query which verify if your user is not already a friend of another first :
INSERT INTO t_friend (userId, friendId)
SELECT 10, 20
WHERE NOT EXISTS ( SELECT userId
FROM t_friend
WHERE userId = 20
AND friendId = 10)
Thanks to this (french) topic about redundancy verification here.

Ordering by a value that is not in the database where selecting from

how would i go about ordering by a value that is not in the table where i am selecting from, in this instance the value $count1 is not in the table search.
count has the same identifying id as that of the thing it is being reffered to in the other table, this is where count1 is grabbed
$q = $db->prepare("SELECT COUNT(rating) FROM ratings WHERE id='$id' AND rating = 'd'");
$q->execute();
$count1 = $q->fetchColumn();
$query = "SELECT * FROM search WHERE title LIKE '$each' ORDER BY '$count1'"
$query = $db->prepare($query);
$query->execute();
that is from ratings, how would i go about ordering the entries like that, so that they are based off the number of count1 and are decided, i might have to implement something like
$query = "SELECT * FROM search WHERE title LIKE '$each' AND id = '$id' ORDER BY '$count1'"
$query = $db->prepare($query);
$query->execute();
Possible Duplicate: Mysql order by specific ID values
Same thing here, you'll just output your $count1as a comma separated string and add it in the SQL query as ORDER BY FIELD(COUNT,___comma_sep_string___)
ratings is a table, not a database. You can join tables or use subqueries to get the desired result, without having to make multiple queries.
You haven't described how the FOREIGN_KEY is set up in the ratings table, but assuming you have something ratings.search_id, this should work:
SELECT search.*, (SELECT COUNT(rating)
FROM ratings
WHERE ratings.search_id = search.id
AND rating = 'd'
) AS rating_count
FROM search
WHERE title LIKE '$each'
ORDER BY rating_count

selecting data from table one table and insert into another table

I have two tables; result and total.
result(student_code,mark)
total(student_code,total)
The total column should contain total marks of a student.
So I have written an SQL statement to insert data from result table into total table by using a SELECT statement which should take a specific student_code and his/her marks as a summation and then store it in the total table.
But, whenever I try, the query either fails or just takes only one student
When I use this query, it works but for only one student, whose student_code is 1, but I need to take all the students and their marks as total
<?php
// copy student student_code and summation of his/her mark from result table into total table
$query = 'INSERT INTO total
(student_code, total)
SELECT student_code, SUM(mark)
FROM
result
WHERE
student_code = 1';
$sql = mysql_query($query) or (mysql_error());
?>
And when I use a student code as a variable I get nothing
<?php
// copy student student_code and summation of his/her mark from result table into total table
$query = 'INSERT INTO total
(student_code, total)
SELECT student_code, SUM(mark)
FROM
result
WHERE
student_code = "' . $student_code . '"';
$sql = mysql_query($query) or (mysql_error());
?>
You must perform two different queries first query selects the data and then store it to a php variable and then later insert it into another table using the second query
UPDATE----
Try this code
<?php
for($i = 1; $i < 102; $i++)
{
$query = 'INSERT INTO total (student_code, total) SELECT student_code, SUM(mark) FROM result WHERE student_code = "$i"';
$sql = mysql_query($query) or (mysql_error());
}
?>
It must work

How can I insert the score into one table as an average of values from another table?

This my first query to insert the scores from the form:
$query1 = "INSERT INTO Category(timing, musicality, technique, difficulty, performance_id)
VALUES ('{$timing}', '{$musicality}', '{$technique}', '{$difficulty}','{$performance}')"
;
This works and it places the scores into a individual scores table, now im trying to take the average of these scores and put them into a table where the contestants information is located, I left a column blank for the scores to go into and heres the query I tried for that:
$query2 = "Insert into Contestants (score) select
sum(timing + musicality + technique + difficulty)/(select count(timing)* 4 from Category where performance_id = '{$performance}')
From Category
WHERE performance_id = '{$performance}';";
Whats happening is, it is inserting the correct average score into the table that I want it to, in the correct field, but instead of updating the row based on the performance_id, it creates a new row. How can I fix this?
Try this:
$query2 = "UPDATE Contestants SET score = (select
sum(timing + musicality + technique + difficulty)/(select count(timing)* 4 from Category where performance_id = '{$performance}')
From Category
WHERE performance_id = '{$performance}')
WHERE performance_id = '{$performance}';";

Categories