JustShiney
JustShiney

Reputation: 13

Sum of one column as another column in phpmyadmin

Using phpmyadmin I am trying to make the sum of one column "PointsAwarded" in one table "tasks" be the values in another column "points" in another table "users". Each user will get points for a task, i want to be able to have the total points they have received be a column in the "user" table. Or an alternative way to show this data in my php datagrid.

new C_DataGrid("SELECT id, FirstName, LastName, Points FROM users", "id", 
"Ranking");

that is the format of the datagrid I am using, it is a phpGrid format. Any help is much appreciated and any further info you need just ask.

Here is the ranking.php page

<?php
// use phpGrid\C_DataGrid;

include_once("../phpGrid/conf.php");
include_once('../inc/head.php');
?>

<h1><a href="../index.php">Staff Rank - Project Management System</a></h1>

<?php
$_GET['currentPage'] = 'ranking';
include_once('../inc/menu.php');
?>

<h3>Ranking</h3>

<?php
$dgRank = new C_DataGrid("SELECT id, FirstName, LastName, Points FROM 
users", "id", "Ranking");
$dgRank->set_col_hidden('id');
$dgRank-> set_sortname('id');
$dgRank->enable_edit();
$dgRank -> display();
?>

<?php
include_once('../inc/footer.php');
?>

Image Album of Database Structure/Relationship https://i.sstatic.net/jENvR.jpg

Album of databases and application: https://i.sstatic.net/zO8Fg.jpg

Upvotes: 0

Views: 1034

Answers (1)

Thomas G
Thomas G

Reputation: 10216

This is a purely database design issue.

Considering that the Points are computed from another table, you should not have this column on your user table. You can DROP it.

The points should be computed in SQL. There are multiple ways to do this and here's an example.

Create a VIEW that computes the points for all users, based on the PointsAwarded for their tasks. Launch this query in phpmyadmin :

CREATE VIEW User_Points AS
SELECT  u.id, SUM(COALESCE(t.PointsAwarded,0)) AS Points 
FROM users 
LEFT JOIN tasks t ON u.id=t.EmployeeID
GROUP BY u.id

Now you can do a SELECT * FROM User_points and that will return something like this:

id  Points
1   48
2   0
3   256
4   125

with id being the id of the user.

Now in the PHP, change your query to this :

SELECT u.id, u.FirstName, u.LastName, p.Points FROM users u INNER JOIN User_points p ON u.id=p.id

and all your issues will be solved

Upvotes: 1

Related Questions