简体   繁体   中英

MySQL Calculate sum of integer values from one column and store the result in another table

I will start with saying I'm new to mysql and I haven't found any answer for my problem here, nor couldn't remake other examples by myself.

I have a table called "profiles" where I store my users, and one of the columns is "points" which stores integers.

I have a second table called "pointsCounter" with only one column "pointsTotal" (also integer) which stores only points from every user on site.

I would like to sum up every user "points" in "profiles" and store the result in "pointsTotal" in table "pointsCounter". I'm making the query using php to then echo the result to file that requests data with ajax.

Example:

profiles

id         |    points    |
---------------------------
1          |     10       |
2          |     20       |
3          |     0        |
4          |     40       |

pointsCounter

pointsTotal  |
--------------
70           |

This is my current not complete php code:

<?php
include 'db_connect.php';

$sql = "SELECT points FROM profiles";
$result = mysqli_query($mysqli, $sql);  //$mysqli is my connection defined in db_connect
if (mysqli_num_rows($result) > 0){
    $points = mysqli_fetch_assoc($result);
}
echo $points['pointsTotal'];

This is probably best handled as a query. Use the SUM() sql function to sum all the points together in the query, as "pointTotal". The rest of the code should work fine.

Try this:

$sql = "SELECT SUM(points) AS pointTotal
FROM profiles"; 

$result = mysqli_query($mysqli, $sql);  //$mysqli is my connection defined in db_connect

if (mysqli_num_rows($result) > 0){
    $points = mysqli_fetch_assoc($result);
}
echo $points['pointTotal'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM