简体   繁体   中英

php mysql calculate each percentage

how do i calculate percentage in mysql for each user?

$q = $db->query("SELECT * FROM report LEFT JOIN user ON user.user_id= report.id_user WHERE date='$today' GROUP BY id_user");
$q1 = $db->query("SELECT SUM(r_amount) AS total FROM report WHERE date='$today' AND id_user=id_user");
$r1 = $q1->fetch_assoc();
$totalCharge = $r1['totalCharge'];
$sixtyPercent = $totalCharge * 0.60;
$fortyPercent = $totalCharge * 0.40;

while($r = $q->fetch_array(MYSQLI_ASSOC)) :
    echo '<tr>';
    echo '<td>'.$r['user_name].'</td>';
    echo '<td align="center">'.$fortyPercent.'</td>';
    echo '<td align="center">'.$sixtyPercent.'</td>';
    echo '<td align="center"><strong></strong></td>';
    echo '</tr>';
endwhile;


current result:

name     60% cut    40% cut    total 
user 1   60         40         100
user 2   60         40         100
user 3   60         40         100

expecting result:

name     60% cut    40% cut    total 
user 1   60         40         100
user 2   24         16         40
user 3   48         32         80

You aren't getting the expected results because your $totalCharge variable will never change (nor will it ever match the proper user_id).

Most likely what you'll want to do is write a SQL statement which combines the two statements you currently have, then simply loop through the results of that statement and do all of the calculations within that loop.

The SQL statement might look something like:

SELECT SUM(r_amount) AS totalCharge, report.*, user.* 
FROM report 
JOIN total ON total.id_user = report.id_user 
LEFT JOIN user ON user.user_id= report.id_user 
WHERE date='$today' GROUP BY user_id

You'll likely have to tweak it a little to get the expected results.

Then your loop will look something like:

while($r = $q->fetch_array(MYSQLI_ASSOC)) {
    $totalCharge = $r['totalCharge'];
    $sixtyPercent = $totalCharge * 0.60;
    $fortyPercent = $totalCharge * 0.40;
    echo '<tr>';
    echo '<td>'.$r['user_name'].'</td>';        // corrected syntax error here
    echo '<td align="center">'.$sixtyPercent.'</td>';
    echo '<td align="center">'.$fortyPercent.'</td>';
    echo '<td align="center"><strong></strong></td>';
    echo '</tr>';
}

Hope this guides you to the solution.

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