Sum fields from different tables per userID - php

Need your help.
php, mysql
I have the following project.
I have two tables
**table 1**
user_id Plan
1 5
1 7
2 5
2 9
3 7
1 9
**table 2**
Plan Price
5 100
7 200
9 300
I must find the total cost of plans selected by one user
eg user_id = 2 must pay 400
I have already the following code, but this one adds the Price of all Plans in database in the above example total cost = 600
What am I doing wrong? :(
$totalcost = NULL;
$sql = "select SUM(Plan.Cost) as ANSWER FROM Plan";
$result = mysql_query($sql, $link) or die(mysql_error());
$totalcost = mysql_fetch_row($result);
$sql = "select * FROM Plan";
$result = mysql_query($sql, $link) or die(mysql_error());
$rows = mysql_num_rows($result);
$Plan = array();
if (is_resource($result)) {
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$Plan[] = $row;
}
}

You have to specify the user_id in your query, like:
$user_id = 2; // or get it from $_GET, $_POST...
$sql = "select SUM(Plan.Cost) as ANSWER
FROM Plan, Users
WHERE Users.Plan = Plan.Plan AND Users.user_id = $user_id";

You probably want to use LEFT JOIN in your query, so you can make something like this:
SELECT table1.user_id, table1.plan, SUM(table2.cost) FROM table1 LEFT JOIN table2 ON table1.plan=table2.plan WHERE table1.user_id = $user_id;
this way you can fetch results in 1 query and make database do all the work instead of looping through data in functions etc.
SQL left join tutorial

Related

i want to select a randomly data using php

I need help in selecting a random data from the table
Let's suppose There are 10 columns in my table but i want that if I hit the query sometime it will bring all data and sometime it will bring data only from 1 column and some time from the no 1 and no 2 column
How can I achieve this?
Thanks in advance
function selectAllInventoriesINGroup($conn,$groupname,$import_id)
{
$cgstSgst = explode('-', $groupname);
$sql = "SELECT * FROM stockitems WHERE generalid = '$import_id' AND cgst = '$cgstSgst[0]' AND sgst = '$cgstSgst[1]' ORDER BY RAND()";
$result = $conn->query($sql);
$jsonxx = mysqli_fetch_all ($result, MYSQLI_ASSOC);
return $jsonxx ;
}
I have tested this but it fetch the all the data from the database
<?php
$sql = "SELECT * FROM stockitems WHERE generalid = '$import_id' AND cgst = '$cgstSgst[0]' AND sgst = '$cgstSgst[1]' ORDER BY RAND()";
?>

getting all mysql results that is less than given id

i am working on a timeline for my website but i am having some problem when i ran the query to select all id that is less than given identifier its still return the identifier result upon every query
example if identifier is id=4 i want to select everything less than 4 and not from 4 > 3 > 2 > 1 i want it to be 3 > 2 > 1
here is my php. i know its not secure or what not but i have written it in prepared statement and get the same thign so i need some here.
if(isSet($_POST['lastmsg']))
{
$feed_id = mysqli_real_escape_string($con, $_POST['lastmsg']);
$get1 = mysqli_query($con, 'SELECT receiver FROM connection where sender="'.$_SESSION['userid'].'"');
$id_feed = array();
while($id_result1 = mysqli_fetch_array($get1)){
$id_feed[] = $id_result1['receiver'];
$ids1 = join(',', $id_feed);
$get_feed1 = mysqli_query ($con, "select * from feed where users in '".$ids1."' or users='".$_SESSION['userid']."' and 'feed_id' < '".$feed_id."' ORDER BY feed_id DESC LIMIT 2");
}
while($res1 = mysqli_fetch_array($get_feed1)){
echo $load = $res1['feed_id'];
}
}

Ranking list with all the users

I have a database (GAMES) with userid, name, sports and points.
user1, football, 10 points -
user1, Basketball, 5 points
user2, footbal, 8 points -
user2, Baketball, 3 points
To get the rank of each user by each sports, I am using the following code which is working perfect:
$sql = "SELECT
sports,
FIND_IN_SET(footbal, (
SELECT GROUP_CONCAT(sports
ORDER BY points DESC)
FROM ".GAMES."
)
) AS rank
FROM ".GAMES."
WHERE userid = 1
";
Results:
user1 (1) (1 is the rank)
When I use user2 in WHERE I get: user2 (2)
Now I want a list like this (For more than 1000 users):
1- User1 (1)
2- User2 (2)
3- User15 (44)
3- ....
Any help will be appreciated. I you need more explanation, just ask.
I would do something like this:
$sqls = array();
foreach ($sports as $sport) {
$sqls[] = "SELECT name FROM ".GAME." WHERE sports='".$sport."' ORDER BY points ASC"
}
Then loop through slqs variable to get all the lists.
And finally, to get the parenthesis part, I would do when I will print the list.
You could have 1 select like this:
$sql = 'SELECT * from table_GAMES WHERE points >= 1000 ORDER BY name'
The result would have all users with more than or equal to 1000 sorted alphabetically. You can then display it like this:
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
echo $row['name'];
echo ' (' . $row['points'] . ')';
}
MySQL does not really implement ranking in a convenient way. This is discussed, for example, here: ROW_NUMBER() in MySQL
In that thread linked above you can see some solutions you could try, or alternatively you could use some simpler SQL to get an ordered list and use PHP to calculate/count the ranks:
// ...
$sql = 'SELECT userid, sports, SUM(points) AS total_points FROM games GROUP BY userid, sports ORDER BY sports, SUM(points) DESC';
$result = $mysqli->query($sql);
$rank = null;
$last_sport = null;
$sports_ranking = array();
while($row = $result->fetch_object()) {
if($row->sports == $last_sport) {
$rank++;
} else {
$rank = 1;
}
$sports_ranking[$row->sports][] = array(
'userid' => $row->userid,
'rank' => $rank,
'total_points' => $row->total_points
);
}
echo('<pre>'); print_r($sports_ranking); echo('</pre>');
// ...
Wouldn't this work?
"SELECT * FROM GAMES WHERE userid = ".$userid." ORDER BY points DESC"
I don't see why you would need to use anything else, as you are just ordering by their points.
or if you also want to specify a sport,
"SELECT * FROM GAMES WHERE userid = ".$userid." AND sports = '".$sport"' ORDER BY points DESC"
You would need to use an array to loop through each sport then just use the above query again.
e.g.
$ranks = mysql_query("SELECT * FROM GAMES WHERE userid = ".$userid." AND sports = '".$sport"' ORDER BY points DESC", $database);
$count = 1;
while(list($userid, $name, $sport, $points) = mysql_fetch_row($ranks)) {
//formatting here. table row, paragraph etc or:
echo "$count - $name ($userid)";
$count++;
}

Get information from MySql Query and put it in PHP array

I have a table of which I must select information using a MySQLi Query and push it to the end of a PHP array.
The table is in this format:
table = friends
id user1 user1_id user2 user2_id datemade accepted
1 name1 1 name2 2 2015-05-27 03:24:32 1
2 name3 3 name2 2 2015-05-27 03:24:32 1
3 name3 3 name1 1 2015-05-27 03:24:32 1
4 name4 4 name2 2 2015-05-27 03:24:32 1
id = an auto_incrementing number to keep track of everything
user1 = the person's name that asks for friendship
user1_id = that person's special unique id
user2 = name of the person that accepts/decline's friendship
user2_id = that person's special unique id
datemade = the date it was made :P
accepted = did he accept? (don't worry about this)
I want to select all users that are friends with $u.
In this example, $u's id is 1 (name is name1).
After running the query it would push it to the end of friend_array.
So if I printed this array the output would be:
2, 3
Since, id=1 is friends with id=2 and id=3
What query should I do and how would I push that to an array (I know about about array_push but I do not know how to implement it)?
Please try this code. It will return the array for all user's friends.
$sql = "SELECT user1 AS user FROM friends UNION SELECT user2 AS user FROM friends";
$data = mysqli_query($sql);
while ($v = mysqli_fetch_assoc($data)) {
$sql = mysqli_query("SELECT * FROM `friends` where (user1 = '" . $v['user'] . "' or user2 = '" . $v['user'] . "')");
$arr = array();
while ($array = mysqli_fetch_assoc($sql)) {
if ($array['user1'] == $v['user']) {
$arr[$v['user']][] = $array['user2_id'];
} else {
$arr[$v['user']][] = $array['user1_id'];
}
}
}
I finally figured it out!
$sql = "SELECT COUNT(id) FROM friends WHERE user1_id='$log_id' AND accepted='1' OR user2_id='$log_id' AND accepted='1'";
$query = mysqli_query($db_conx, $sql);
$query_count = mysqli_fetch_row($query);
$friend_count = $query_count[0];
//echo($friend_count); //how many friends
if($friend_count < 1){
echo($u." has no friends yet");
} else {
$all_friends = array();
$sql = "SELECT user1_id FROM friends WHERE user2_id='$log_id' AND accepted='1' ORDER BY RAND()";
$query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
array_push($all_friends, $row["user1_id"]);
}
$sql = "SELECT user2_id FROM friends WHERE user1_id='$log_id' AND accepted='1' ORDER BY RAND()";
$query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
array_push($all_friends, $row["user2_id"]);
}
$friendArrayCount = count($all_friends);
}
So it first counts how many friends you have to check if you have any, if you do not a, temp. message appearing saying no friends. If you have some friends it will run a query to check what friends you have is both columns - user1_id and user2_id. It will then finally add everything to the $all_friends array and it then counts how many friends you have.
Thank you to everyone that helped!

PHP/MySQL Update query every 2 column update room change automated

I want to create automated room divisions.
Assumptions :
I have 4 data.
Each room maximum 2 people.
If room is full / reach max "2", 3th people automated insert to the next room.
Here my code. assumption 4 data.
$kuota=2; //Max 2 data in 1 room
while ($row = mysqli_fetch_array($query)) {
$id = $row["id"];
$x=1;
while($x<=$kuota) {
$sql2 = "UPDATE cds SET room=$y WHERE id='$id'";
$query2 = mysqli_query($con, $sql2) or die (mysqli_error($con));
$x++;
}
$y++
}
but it doesn't work.
My code is so ugly :(
I want to get a result like this
name || Room
Michael || 1
Muller || 1
...
Cyntia || 2
Gina || 2
while ($row = mysqli_fetch_assoc($query)) {
$id = $row['id'];
$sql2 = "UPDATE cds AS c1
CROSS JOIN (SELECT room
FROM cds
GROUP BY room
HAVING COUNT(*) < $kuota
ORDER BY room
LIMIT 1) AS c2
SET c1.room = c2.room
WHERE id = $id";
mysqli_query($con, $sql2) or die (mysqli_error($con));
}
The c2 subquery returns the first room that has fewer than $kuota people assigned to it.

Categories